【问题标题】:setting state in axios.get(url).then() does not work when using react redux使用 react redux 时在 axios.get(url).then() 中设置状态不起作用
【发布时间】:2019-11-07 12:50:09
【问题描述】:

在使用 ReactRedux 时,我遇到了这个有趣的现象。

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {fetchBooks} from '../actions'

class Sample extends Component {

    componentDidMount() {
        /* Fetching from server */
    }

    render(){
        return(
            {this.props.books.map(book => <Book key={book.title} {...book} />)}
        )
    }
}

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({fetchBooks}, dispatch);
}

const mapStateToProps = ({books}) => {
    return {books};
}

connect(mapStateToProps, mapDispatchToProps)(Sample)

当我用 redux as 实现componentDidMount() 函数时

...
componentDidMount() {
    this.props.fetchBooks();
}
...

状态被更新,渲染函数被调用。

但是,当我将 axios 与 promise 一起使用时,它不起作用:

import axios from 'axios';
...
componentDidMount() {
    const self = this;
    axios.get(__URL__)
        .then((response) => {
            self.setState({books: response.data});
        });
}
...
  1. 这是否意味着您在使用 redux 时不能混合使用这两种方式来设置状态?
  2. 或者当使用 redux 时,为什么一种方法有效而另一种方法无效?

【问题讨论】:

  • 请注意,redux 状态与 component 状态非常不同。
  • 您的答案在jonrsharpe's comment。您将 redux 存储状态与 React 组件状态混淆了。将this.props.books 更改为this.state.books 应该足以证明它有效。
  • 是的。谢谢@jonrsharpe 和埃米尔。这实际上是结帐。我曾希望组件状态被传播到 redux 状态。
  • “我曾希望组件状态被传播到 redux 状态。” 这将完全违背 Redux 的目的。但是,您可以触发从组件中获取有效负载的操作,例如this.props.setBooks(response.data).

标签: javascript reactjs react-redux axios


【解决方案1】:

好吧,你错过了 component 状态和 redux 状态的混乱。当你使用 redux 调用 dispatch 函数时:

componentDidMount() {
  this.props.fetchBooks();
}

它调度 action 函数并更新 redux 状态。通过在

处传递第一个参数,从组件 props 中捕获 redux 状态
connect(mapStateToProps, mapDispatchToProps)(Sample)

当您在获得 axios 响应后调用 setState 时,它会更新您的 component 状态而不是 redux 状态。因此,在这种情况下,您可能会从 this.state.books 而不是 this.props.books 找到您的数据。如果需要在 axios 得到响应时调度 action 函数。

componentDidMount() {
  const self = this;
  axios.get(__URL__)
    .then((response) => {
        //self.setState({books: response.data});
        self.props.yourDispatchFunctionWithPassingTheReponseData(response.data);
    });
}

更多派送信息,请查看link

【讨论】:

    猜你喜欢
    • 2019-01-17
    • 2021-06-19
    • 1970-01-01
    • 2019-08-10
    • 2023-01-15
    • 1970-01-01
    • 2018-12-09
    • 2018-01-05
    • 1970-01-01
    相关资源
    最近更新 更多