javascript - react /Redux : modified state is not updated in view

标签 javascript reactjs react-native redux

在我使用 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);

所以最终状态如下所示:

enter image description here

在我的应用程序组件的渲染方法中,我将状态传递给子组件:

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/

相关文章:

android - React native android 转换真的很慢

javascript - 在 Three.js 中加载 JSON 模型

javascript - 如何在 Redux 中集成 FileReader?

javascript - Gatsby 开发失败 : Error: Cannot find module 'gatsby-cli/lib/reporter'

javascript - 当某些列的数据缺失时在表中创建行

ios - FlatList onRefresh 不适用于 SafeAreaView

javascript - 如何使用 React Native Navigation (v5) 向父页面发送数据?

javascript - 如何让程序等待 javascript 中的按钮按下?

javascript - 为动态子项添加唯一键,而无需任何唯一键

javascript - 使用 Nan 检查 node.js 插件中的 instanceof