reactjs - previous state is rendering (duplicate) with new state -
i having trouble figuring out why component renders both previous prop , new prop instead of diff.
for example renders:
[[1, 2, 3, 4, 5]] [[6, 7, 8, 9, 10]] [[1, 2, 3, 4, 5]] [[6, 7, 8, 9, 10]] [[16, 57, 8, 19, 5]]
instead of just:
[[1, 2, 3, 4, 5]] [[6, 7, 8, 9, 10]] [[16, 57, 8, 19, 5]]
my main component:
class asyncapp extends component { constructor(props) { super(props) } lookforupdate() { // function hits endpoint every 10 sec. setinterval(() => { this.props.dispatch(fetchdataforreals()) }, 10000) } componentdidmount() { this.props.dispatch(fetchdataforreals()) this.lookforupdate() } render() { const { graphdata } = this.props; return ( <div> <div>hello</div> <datagraph graphdata={graphdata} /> </div> ) } } function mapstatetoprops(state) { let graphdata = state.payment.graphdatas return { graphdata } } export default connect(mapstatetoprops)(asyncapp)
my other component:
import react, { component } 'react' export default class datagraph extends component { constructor(props) { super(props) } shouldcomponentupdate(nextprops) { return nextprops.graphdata !== this.props.graphdata } render() { return ( <div>{this.props.graphdata.map(function(datas){ return datas.map(function(data, index){ return <li key={index}>{data.series}</li> }) })}</div> ) } } export default datagraph;
my action.js
function requestdataarray() { return { type: request_data } } function recievedataarray(data) { return { type: recieve_data, data: data.map(child => child), receivedat: date.now() } } function fetchdata() { return dispatch => { dispatch(requestdataarray()) return fetch('//localhost:3000/api/v1/data', { mode: 'no-cors' }).then(function(data){ return data.json() }).then(function(data){ dispatch(recievedataarray(data)) }) } } export function fetchdataforreals() { return (dispatch) => { return dispatch(fetchdata()) } }
my reducers:
const initialstate = { graphdatas: [], friendslist : {}, comments: [] } function adddata(state = initialstate.graphdatas, action) { switch(action.type) { case 'recieve_data': var clone = _.clonedeep(state); var resultpopoff = clone.pop() let stateresult = _.isequal(resultpopoff, action.data) if (stateresult) { return state } else { return [ ...state, action.data ] } default: return state; } } const payment = (state = initialstate, action) => { switch(action.type) { default: return { graphdatas: adddata(state.graphdatas, action) } } } const rootreducer = combinereducers({ payment, routing: routerreducer }) export default rootreducer
i think you're doing in reducer:
return [ ...state, action.data ]
you should returning clone pop()
ed off:
return [ ...clone, action.data ]
Comments
Post a Comment