在我使用 redux 的 React Native 应用程序中, reducer 似乎工作正常,但 UI 不会根据状态修改进行更新。
这是我的 reducer :
const initialState = {
userId: 1,
userName: "nobody",
showIntroOnNextStart: true
}
export default function reducer(state = initialState, action) {
switch(action.type) {
case 'INCREMENT':
let newState = {
...state,
userId: state.userId + 1
};
console.log(newState);
return newState;
}
return state;
}
它将通过以下方式导出和导入:
import userProfile from './userProfile'
export { userProfile }
这是我的连接方法:
export default connect(state => ({
state: state.userProfile
}),
(dispatch) => ({
actions: bindActionCreators(actions, dispatch)
})
)(ApplicationContainer);
所以最终状态如下所示:
在我的应用程序组件的渲染方法中,我将状态传递给子组件:
render() {
const { state, actions } = this.props;
return ....lots of scenes...
<Scene key="home" component={HomeScreen} title="Home" state={state} {...actions} />
在特定的场景组件中,我使用这样的状态:
render(){
const { state, decrement, increment } = this.props;
return (
<View {...this.props} style={styles.container}>
<Text>{state.userId}</Text>
<Button onPress={increment}>Increment</Button>
</View>
);
}
增量操作按预期正常工作,每个 console.log-Output 显示一个具有正确增量值的新状态对象。
但是 View 不会更新。 在reducer函数中,状态按预期工作并在每次调用时递增userId。但在渲染函数中,状态对象值从一开始就保持不变。
这里可能出了什么问题?
更新
当我从react-native-router-flux中删除这个Router-Stuff时,一切正常。状态将是相同的实例并且将被更新。但是一旦将组件封装到路由器的场景中,状态更新就不会发生
最佳答案
从我有限的 Redux 时间来看,不渲染的问题通常是对象的引用没有改变。如果您有深层对象,则需要进行深层复制。我个人喜欢对 React 中的任何状态使用 immutable.js。
您可以尝试缩小问题范围的另一件事是在按 Increment 后在组件上调用 this.forceUpdate()。如果它更新了 View ,这将使您更接近找出问题所在。
关于javascript - react /Redux : modified state is not updated in view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37241194/