在React Native中更改/更新Redux存储中的值,可以按照以下步骤进行:
npm install redux react-redux
createStore
函数来创建store,并将reducer传递给它。reducer是一个纯函数,用于处理不同的action并更新store中的状态。import { createStore } from 'redux';
// 定义初始状态
const initialState = {
value: ''
};
// 定义reducer
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'UPDATE_VALUE':
return {
...state,
value: action.payload
};
default:
return state;
}
};
// 创建store
const store = createStore(reducer);
connect
函数将组件连接到Redux store,并使用mapStateToProps
和mapDispatchToProps
函数来映射store中的状态和操作到组件的props。import React from 'react';
import { View, Text, TextInput, Button } from 'react-native';
import { connect } from 'react-redux';
// 定义组件
class MyComponent extends React.Component {
handleChange = (value) => {
// 调用action更新store中的值
this.props.updateValue(value);
}
render() {
return (
<View>
<TextInput
value={this.props.value}
onChangeText={this.handleChange}
/>
<Text>{this.props.value}</Text>
</View>
);
}
}
// 映射store中的状态到组件的props
const mapStateToProps = (state) => ({
value: state.value
});
// 映射操作到组件的props
const mapDispatchToProps = (dispatch) => ({
updateValue: (value) => dispatch({ type: 'UPDATE_VALUE', payload: value })
});
// 使用connect函数连接组件和Redux store
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
在上述代码中,MyComponent
组件通过connect
函数连接到Redux store,并使用mapStateToProps
函数将store中的value
状态映射到组件的props中。同时,使用mapDispatchToProps
函数将updateValue
操作映射到组件的props中,以便在组件中调用该操作来更新store中的值。
这样,当TextInput的值发生变化时,调用handleChange
方法会触发updateValue
操作,从而更新store中的值。组件中的Text会自动更新为最新的值。
推荐的腾讯云相关产品:无
希望以上信息对您有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云