为了账号安全,请及时绑定邮箱和手机立即绑定

为什么在使用 thunk 时会以错误的顺序调用我的动作创建者?

为什么在使用 thunk 时会以错误的顺序调用我的动作创建者?

神不在的星期二 2023-10-14 11:16:18
我正在尝试 redux-thunk 和动作创建者,并注意到一些我不理解的奇怪行为。当我调用动作创建器函数时,它们不会按照我希望的顺序调用。这是我的 App.js 组件class App extends Component {  handleSave = () => {    this.props.postData({      name:this.props.activity,      type_name: this.props.type    })    this.props.fetchList()    this.props.fetchData()  }  handleClick = () => {    this.props.fetchData()  }  componentDidMount() {    this.props.fetchData()    this.props.fetchList()  }  render() {    return (      <div className="App">        <Router>          <Nav />          <Route exact path='/' render={props => <Home {...props} clickProp={this.handleClick} saveProp={this.handleSave}/>} />          <Route exact path='/activities' render={props => <ListContainer {...props} numItems={this.props.list.length} listProp={this.props.list}/>} />        </Router>      </div>    );  }}const mapStateToProps = state => {  return {    activity: state.activity,    type: state.type,    list: state.list  }}const actions = {fetchData, fetchList, postData}export default connect(mapStateToProps, actions)(App);当我单击 Home 子组件中的按钮时,将调用 handleSave 函数,然后该函数应该将一个项目发布到我的列表中,然后获取更新的列表,以便它可以显示在我的列表中。当我这样做时, this.props.fetchList() 首先被调用,即使它是第二个被调用的函数。我在我的减速器中放置了一个 console.log(action) ,这就是打印的内容。{type: "FETCH_LIST", payload: Array(86)}{type: "POST_DATA", payload: {…}}{type: "FETCH_DATA", payload: {…}}我可以让 FETCH_LIST 在 POST_DATA 之后发生的唯一方法是如果我像这样第二次调用 fetch_data()  handleSave = () => {    // something weird going on here    this.props.fetchList()    this.props.postData({      name:this.props.activity,      type_name: this.props.type    })    this.props.fetchList()    this.props.fetchData()  }如果可能的话,我真的希望能够让我的代码正常工作,而不必两次调用同一个函数。最后,这就是我的动作创建者的样子。export default function fetchData() {  return (dispatch) => {    const url = 'http://www.boredapi.com/api/activity/'    fetch(url)      .then(res => res.json())      .then(activity => { dispatch({type: "FETCH_DATA", payload: activity})})  }}我唯一的猜测是,发生这种情况是因为这些操作是异步的。所以我也尝试改变这些函数的调用顺序,无论什么 FETCH_LIST 总是发生在 POST_DATA 之前。
查看完整描述

1 回答

?
BIG阳

TA贡献1859条经验 获得超6个赞

您可以将这些操作创建者转换为async版本,然后您可以等待它们,以便它们按顺序执行。


https://medium.com/@gaurav5430/async-await-with-redux-thunk-fff59d7be093


例如在你的fetchData


function fetchData() {

  return async (dispatch) => {

    const url = 'http://www.boredapi.com/api/activity/'


    try{

      const res = await fetch(url)

      const activity = await res.json();

      dispatch({type: "FETCH_DATA", payload: activity})

    }

    catch (error) {

      console.log(error);

    }

}

一旦它们出现,async您就可以在您的中等待它们handleSave(一旦您将其转换为async),这将确保它们按顺序被调用。


handleSave = async () => {

    await this.props.postData({

      name:this.props.activity,

      type_name: this.props.type

    })

    await this.props.fetchList()

    await this.props.fetchData()

  }


查看完整回答
反对 回复 2023-10-14
  • 1 回答
  • 0 关注
  • 58 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信