Answer the question
In order to leave comments, you need to log in
How to change state on page load in React - Redux - Router?
I'm trying to update the title when switching between pages. The page title is stored in the global state and rendered in the Header component. Tried like this
const List = ({ onPageLoad }) => {
return (<div>{onPageLoad('Page list')}</div>);
}
const mapDispatchToProps = (dispatch) => ({
onPageLoad: (title) => {
dispatch({type:'SET_TITLE', title});
}
});
Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.
Answer the question
In order to leave comments, you need to log in
it's not entirely clear what this component renders if the title is rendered in another component? I'll just return null, and then you figure it out yourself.
import React from 'react';
import { connect } from 'react-redux';
class List extends React.Component {
componentDidMount() {
this.props.onPageLoad('Page list');
}
render() {
return null;
}
}
const mapDispatchToProps = (dispatch) => ({
onPageLoad: (title) => {
dispatch({type:'SET_TITLE', title});
}
});
export default connect(null, mapDispatchToProps)(List);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question