【发布时间】:2018-06-11 10:43:39
【问题描述】:
tl;dr 我正在尝试将初始状态保存在子容器组件中,但每次 Redux 存储更新时它都会更新为新值。我可能在配置中遗漏了一些东西,我需要帮助来解决问题。
index.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)
Actions.ts
function detailsUpdate(props: UpdateProps): UpdateUserDetails {
return {
type: UPDATE_USER_DETAILS,
props: { ... }
}
}
Reducers.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;
}
App.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 组件通常为 <input type="text"> 呈现另一个表示组件,为简洁起见,我在此省略。
谢谢!
【问题讨论】:
-
你在使用 combine reducer 吗?
-
@Prabhu:我没有使用 combineReducers,但使用 reducer 有不同的方法。我用商店创建和 reducers.ts 示例更新了问题。
标签: reactjs redux react-redux