【发布时间】:2016-05-15 17:04:16
【问题描述】:
在我使用 redux 的 react native 应用程序中,reducer 似乎工作正常,但 UI 不会在状态修改时更新。
这是我的减速器:
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 都会显示一个具有正确增量值的新状态对象。
但视图不会更新。 在 reducer 函数中,状态按预期工作,并在每次调用时递增 userId。但在渲染函数中,状态对象的值从一开始就保持不变。
这里可能出了什么问题?
更新
当我从 react-native-router-flux 中删除这个 Router-Stuff 时,一切正常。状态将是相同的实例并将被更新。但是一旦将组件封装到路由器的场景中,状态更新就不会发生
【问题讨论】:
-
你有没有试过
console.log你传递给渲染函数的props?如果它没有像一个动作发生那样频繁地记录,可能是你定义了一个 shouldComponentUpdate 函数,它跳过了更新? -
只是一个评论;当您使用 state 作为 props 变量时,这会令人困惑。您应该尝试找到适合您设计的另一个名称。
标签: javascript reactjs react-native redux