reactjs - confusing about load data based on router params in react component -
i want load data api based on router params in component,
the channel page behave expected when first open page, if go other channel page clicking, channelpage
component didn't call componentdidmount
, reducer received fetch_messages
action, sidebar
component have problem. redux-devtools can received location_change
action when other channel page clicked. it's weird!
what's best practice loading data based on params in react component?
sidebar
class sidebar extends react.component { componentdidmount() { this.props.fetchchannels(1); } openchannelpage = (e, url) => { e.preventdefault(); console.log('open channel page'); this.props.changeroute(url); }; render() { let channelscontent = null; if (this.props.channels !== false) { channelscontent = this.props.channels.map((item, index) => ( <channelitem routeparams={this.props.params} item={item} key={`item-${index}`} href={item.url} handleroute={(e) => this.openchannelpage(e, item.url)} /> ), this); } return ( <div id="direct_messages"> <h2 classname={styles.channels_header}>messages</h2> <ul> {channelscontent} </ul> </div> ); } } const mapstatetoprops = createstructuredselector({ channels: selectchannels(), }); const mapdispatchtoprops = (dispatch) => ({ changeroute: (url) => dispatch(push(url)), fetchchannels: () => dispatch(fetchchannels()), }); export default connect(mapstatetoprops, mapdispatchtoprops)(sidebar);
channelpage
class channelpage extends react.component { componentdidmount() { console.log('##fetch history messages##'); this.props.fetchmessages(this.props.channel); } render() { return ( {this.props.channel.name} ); } } const mapstatetoprops = createstructuredselector({ channel: selectchannel(), }); export default connect(mapstatetoprops, { fetchmessages, })(channelpage);
appreducer
function appreducer(state = initialstate, action) { switch (action.type) { case receive_channels: console.log('received channels'); return state; case fetch_channels: console.log('fetching channels'); return state; case fetch_messages: console.log('fetching history messages---wtf'); return state; default: return state; } } export default appreducer;
reducer received unexpected fetch_messages
action
redux-devtools can received location_change
action when go other channel page
which 1 right behavior?
there 2 questions
what's best practice loading data based on params in react component?
you can use componentdidupdate() dispatch request based on router params data api
reducer received unexpected
fetch_messages
action when navigatemessages/1
messages/2
it's expected behavior, reducer receive previous action when navigate messages/1
messages/2
, , componentdidmount
ran once never called
Comments
Post a Comment