A
A
Andrey2017-02-22 00:17:56
React
Andrey, 2017-02-22 00:17:56

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});
    }
});

title is updated but swears in console
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`.

how to update it correctly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Islam Ibakaev, 2017-02-22
@flx12

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);

H
Hazrat Hajikerimov, 2017-02-22
@hazratgs

call the desired action in the container constructor

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question