所以我试图将元素添加到我存储在状态中的数组中。我知道你不应该直接改变状态,所以我发现使用 concat
是最好的方法。
但是,当我尝试这样做时,我遇到了无限循环。
reducer .js:
const initialState = {
name : null, //puzzle name
start : []
};
export default createReducer(initialState,{
[START_PROCESS]: (state,payload) => {
return Object.assign({},state,{
start : state.start.concat(['test']);
})
}
});
结果是['test','test','test','test'...
例如:
- 设置
start:state.start
有效 - 设置
start: state.start + 'test'
会导致testtesttest..
无限循环
我不知道是什么导致了这种奇怪的行为。据我所知,状态只能通过创建一个新状态来修改,因此它无法反馈到自身。
createReducer.js
export function createReducer(initialState, reducerMap) {
return (state = initialState, action) => {
const reducer = reducerMap[action.type];
return reducer
? reducer(state, action.payload)
: state;
};
}
startAction.js
const START_PROCESS = 'START_PROCESS';
export function startProcess(data) {
return {
type : START_PROCESS,
payload : {
data : data //where data is a string
}
}
}
viewAction.js
...
export default ProcessView extends React.Component {
render() { return <div>{this.props.actions.startProcess('string')}</div> }
}
export default connect(mapStateToProps,mapDispatchToProps)(ProcessView)
最佳答案
避免状态突变的最佳方法肯定是 ImmutableJS 。就你而言,我想说也许你认为你的行为是错误的。你确定它不是在渲染内部调用的吗?
关于javascript - React-Redux : Infinite loop when concat to an array in state?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36106282/