reactjs - 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">
为简洁起见,我在此省略。
谢谢!
解决方案
以下仅制作状态对象的浅表副本。
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-一级的
推荐阅读
- c# - 刷新 CarouselView 项目后保持当前位置
- java - Java 证书、Eclipse 和 Maven:PKIX 路径构建失败
- python - RDD转Rows时如何自动添加列名?
- python - 熊猫在列长度不等的数据框中迭代列的空单元格
- aws-cdk - 是否可以在 cdk8s 中指定 AWS 资源?
- javascript - Vue JS 无法将 innerHTML 的属性设置为 null
- ipfs - 将文件夹中的文件固定到 pinata 上的 IPFS 时,是什么决定了 gateway.pinata.cloud/ipfs 链接?
- web - 在 Cloud Foundry 上部署 Web 应用程序给出 fileNotFoundException
- python - 带有 API 谷歌表的 Discord Bot
- google-apps-script - Google 表格 - 按钮不断移动