I am starter in react & redux. I want to make todolist app. but when I insert a list into a store the displayList() function is not re-render. How can I fix this.
This is my reducer code.
export default function(state = ['start1','start2'], actions) { switch(actions.type) { case 'APPEND_ITEM': state.push(actions.payload.item) return state break } return state }
And this is my todolist.js code.
import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import ReactDOM from 'react-dom' import React from 'react' class TodoList extends React.Component { displayList(){ return this.props.dispatchs.map((item) => { return( <li key={ Math.random() }>{item}</li> ) }) } render(){ return( <div> { this.displayList() } </div> ) } } var mapStateToProps = (state) => { return { dispatchs: state.dispatch } } export default connect(mapStateToProps)(TodoList)
pin 2,3 does not re-render on the screen
Thank you for help.
Instead of using push in the reducer, return [ ... state, action.payload.item ]
case 'APPEND_ITEM':
return [ ...state, action.payload.item ]
This is because React will see the new state (object reference) equal to the old one, and decide not to re-render since it seems like nothing have changed
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.