首页 > 解决方案 > React-Redux 组件状态

问题描述

tl; dr 我试图将初始状态保存在子容器组件中,但每次 Redux 存储更新时它都会更新为新值。我可能在配置中遗漏了一些东西,我需要帮助来解决问题。

索引.tsx

const store = createStore(reducers, loadedState, enhancer);
ReactDOM.render(
    <Provider store={store}>
      <App />
    </Provider>,
    document.getElementById(containerId)
)

AppProps.ts

function mapStateToProps(state: StoreState){
  return{
    ... // app props
    userDetails: state.userDetails // array of objects fetched by id
  }
}

function mapDispatchToProps(dispatch: ReactRedux.Dispatch<actions.AppActions>){
  return{
    ... // app methods
    detailsUpdate: (props: UpdateProps) => (dispatch(actions.detailsUpdate(props: UpdateProps)))
  }
}
ReactRedux.connect(mapStateToProps, mapDispatchToProps)(App)

动作.ts

function detailsUpdate(props: UpdateProps): UpdateUserDetails {
    return {
        type: UPDATE_USER_DETAILS,
        props: { ... }
    }
}

减速器.ts

export function reducers(state: StoreState, action: actions.AppActions): StoreState {    
    let newState: StoreState =  {...state};
    switch (action.type) {
        case actions.UPDATE_USER_DETAILS:
        ... // reducer code
        break;
        case actions.UPDATE_PRODUCTS:
        ... // reducer code
        break;
    return newState;
}

应用程序.tsx

const App = (allProps: IAppProps, state: StoreState) => {
  <UserDetailsContainer
    id="generalDetails"
    userDetails={allProps.userDetails.byId}
    detailsUpdate={allProps.detailsUpdate}
  />
}

UserDetailsContainer.tsx 1

class UserDetailsContainer extends
React.Component<UserDetailsContainerProps, UserDetailsState> {    
    constructor(props: UserDetailsContainerProps) {
        super(props);      
        this.state = {
            userData: props.userDetails[props.id]
        }
    }

    render(){
       <input type="text"
        value={this.props.userDetails[this.props.id].address}
      />
    }
}

detailsUpdate 触发 UPDATE_USER_DETAILS 操作,reducer 使用新值更新存储状态。现在,UserDetailsContainer 从商店接收更新版本的 userDetails,这可以很好地在<input type="text">元素中显示新值。

但是,this.state 会更新为我认为不应该发生的新值,因为构造函数应该只被调用一次(并且是)。这可以防止我在需要重置或其他时引用初始值。

请询问任何缺失的信息和/或澄清,并忽略任何拼写错误,因为该应用程序正常工作,否则不会出现错误。

1 Component 通常会渲染另一个展示组件,<input type="text">为简洁起见,我在此省略。

谢谢!

标签: reactjsreduxreact-redux

解决方案


以下仅制作状态对象的浅表副本。

let newState: StoreState =  {...state};

所以如果你分配

this.state = {
   userData: props.userDetails[props.id]
}

然后修改 reducer 中的数组,您还将修改组件的状态,因为它引用了同一个对象。这也违背了 redux 的概念——reducer 不应该改变它的论点。

请注意,这个确切的错误在 redux 文档中突出显示:https ://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#common-mistake-2-only-making-a-shallow-copy-一级的


推荐阅读