Ad
React-Redux: Infinite Loop When Concat To An Array In State?
So I am trying to add elements to an array I have stored in the state. I know you are not supposed to mutate the state directly, so I found that using concat
is the best way of doing it.
However when I try doing this, I get an infinite loop.
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']);
})
}
});
the result is ['test','test','test','test'...
e.g:
- setting
start: state.start
works - setting
start: state.start + 'test'
results in an infinite loop oftesttesttest..
I don't know what causes this weird behavior. From what I know the state is only modified this way by creating a new state so there is no way it could feed back into itself.
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)
Ad
Answer
The best way of avoiding state mutation is definitely with ImmutableJS. In your case I would say that maybe you call your action wrong. Are you sure it is not called inside render?
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad