Joh*_*Doe 0 javascript state reactjs redux react-redux
Redux已成功存储和更新状态。减速器似乎正常工作。我可以使用this.props.dispatch。但是,当涉及到详细说明该信息时(即,this.props.array我似乎总是不确定)。
减速器:
export default function array(state = {}, action) {
switch (action.type) {
case "UPDATE_ARRAY":
state.array = action.array
return state;
default:
return state;
}
}
Run Code Online (Sandbox Code Playgroud)
状态感知组件:
constructor(props) {
super(props);
this.state = {
array: array
}
}
Run Code Online (Sandbox Code Playgroud)
-
self.props.dispatch({
type: 'UPDATE_ARRAY',
array: array
})
Run Code Online (Sandbox Code Playgroud)
-
const mapStateToProps = (state) => {
return {
messages: state.messages,
array: state.array
};
};
export default connect(mapStateToProps)(Component);
Run Code Online (Sandbox Code Playgroud)
当我定义一个空数组时,这似乎只能保存状态btw。这似乎不对,我认为Redux的初衷是一个独立的商店?更新变量似乎会破坏目标。
将不胜感激。
export default function array(state = {}, action) {
switch (action.type) {
case "UPDATE_ARRAY":state={
...state,
array:action.array
}
return state;
default:
return state;
Run Code Online (Sandbox Code Playgroud)
}}
我不确定您的应用程序是否具有多个reducer,如果具有,则必须使用Combine reducer方法。因此在mapsStateToProps中访问state.array就像这样
const mapStateToProps =(state)=> {return {
messages: state.{reducer_name}.message,
array: state.{reducer_name}.array
Run Code Online (Sandbox Code Playgroud)
}; };
代替“ reducer_name”,您必须指定在组合减速器中定义的reducers_name
最后一个mapStateToProps返回数组,在props中不处于组件状态。您可以通过{this.props.array}这样的方式进行访问,您无法在componentDidMount和componentWillRecieveProps中设置组件状态(如果aysnc操作)。