Проблема с состоянием реакции, которое не обновляется/не увеличивается

Я пытаюсь разбить на страницы, щелкнув текст, который вызывает метод для увеличения значения состояния. Затем значение состояния передается вызову axios, который затем должен вызвать следующую страницу. Однако я замечаю, что, хотя состояние увеличивается в console.log из функции рендеринга, вызов axios не вызывается снова с новым значением состояния. Кто-нибудь знает, как я могу это исправить?

constructor(props) {
    super(props);
    this.state = {
        people: [],
        planets: [],
        page: 1
    };
    this.pageIncrementer = this.pageIncrementer.bind(this);
}

componentWillMount() {
    let page = this.state.page;
    axios({
        method: 'GET',
        url: `http://localhost:3008/people?_page=${page}&_limit=10`
    }).then((response) => {
        this.setState({
            people: response
        });
    }).catch((error) => {
        console.log('There is an error in the Card axios call for people: ', error);
    })
    axios({
        method: 'GET',
        url: `http://localhost:3008/planets?_page=${page}&_limit=10`
    }).then((response) => {
        this.setState({
            planets: response
        });
    }).catch((error) => {
        console.log('There is an error in the Card axios call for planets: ', error);
    })
}

pageIncrementer() {
    this.setState({
        page: this.state.page + 1
    });
}


person Milos    schedule 24.07.2017    source источник


Ответы (1)


componentWillMount вызывается только один раз, вам нужно componentDidUpdate https://facebook.github.io/react/docs/react-component.html#componentdidupdate

let getData = () => Math.random();

class Example extends React.Component{
        constructor(props) {
          super(props);
          this.handleChange = this.handleChange.bind(this)
          this.state = {
                name: ''
          };
        }

        componentWillMount(){
             console.log('componentWillMount')
        }

        componentDidUpdate(){
             console.log('componentDidUpdate') 
        }

        handleChange(e) {
          this.setState({
            name: this.props.getData()
          });
        }


        render() {
            return <div className="widget"> 
            {this.state.name}
            <button onClick={this.handleChange}>Inc</button>

            </div>;
        }
      }

      React.render(<Example getData={getData}/>, document.getElementById('container'));

Изменить (альтернативный способ):

let getData = () => Math.random();

class Example extends React.Component{
        constructor(props) {
          super(props);
          this.makeRequest = this.makeRequest.bind(this)
          this.state = {
                page:1,
                name:''
          };
        }

        makeRequest(next){
             fetch('https://jsonplaceholder.typicode.com/posts/'+this.state.page)
             .then(
                result => {
                 console.log('do')
                 return result.json()}
             )
             .then(
                 (resp) => this.setState({
                 name:resp, page:this.state.page+1})
             )
        }


        render() {
            return <div className="widget"> 
            {this.state.name}
            <button onClick={this.makeRequest}>Request</button>

            </div>;
        }
      }

      React.render(<Example getData={getData}/>, document.getElementById('container'));
person Anatoly Strashkevich    schedule 24.07.2017
comment
Не могли бы вы привести пример из моего кода, как я буду использовать обновление componentDid? Я не слишком знаком с этим и был бы очень признателен. - person Milos; 24.07.2017
comment
Я заставляю работать разбивку на страницы, но, похоже, она находится в бесконечном цикле, и я даже не нажимаю кнопку следующей страницы. NVM Я понял, спасибо за вашу помощь, мне пришлось добавить условное условие if в componentdidmount, чтобы проверить состояния, если они изменились. - person Milos; 24.07.2017