【问题标题】:How to pass async data to dispatch action so I can use it in action creator?如何将异步数据传递给调度动作,以便我可以在动作创建者中使用它?
【发布时间】:2018-10-08 11:43:21
【问题描述】:

Redux 是 harrrrd... 至少对我来说,它是!!!有人可以向我解释如何通过 mapDispatchToProps 将获取的 json[0] 传递给我的动作创建者吗?我做得对吗?我正在使用 redux-thunk,这是正确的使用方式吗?

state = {
    articles: {
      article: []
    }
  };

  qrCodeOnReadHandler = ({ data }) => {
    this.props.onQRRead();
    console.log(this.props.art);
    fetch(data)
      .then(response => response.json())
      .then(json => {
        console.log(json),
          // () => this.props.onQRRead(json[0]),
          this.setState({
            ...this.state,
            articles: {
              ...this.state.articles,
              article: json[0]
            }
          });
      });
  };

连接redux

const mapStateToProps = state => {
  return {
    art: state.articles.article
  };
};
const mapDispatchToProps = dispatch => {
  return {
    onQRRead: () => dispatch(article())
  };
};

动作创建者

export const fetchedArticle = res => {
  return {
    type: ARTICLE,
    res: res
  };
};

export const article = res => {
  return dispatch => {
    dispatch(fetchedArticle(res));
  };

};

【问题讨论】:

    标签: reactjs react-native redux redux-thunk


    【解决方案1】:

    如何通过 mapDispatchToProps 将获取的 json[0] 传递给我的 动作创建者

    你必须让你的onQRRead 收到这样的参数:

    const mapDispatchToProps = dispatch => {
      return {
        onQRRead: payload => dispatch(article(payload))
      };
    };
    

    函数参数的名称是任意的。

    现在,您可以像刚才那样使用它:

    this.props.onQRRead(json[0])
    

    【讨论】:

    • 嗨 Nguyễn Thanh Tú,但我应该在 fetch 中使用 onQRRead 吗?因为当我像这样使用它时 id 没有传递参数,实际上它并没有调度一个动作。你能建议我在哪里使用 this.props.onQRRead(json[0]) 吗?
    • 请提供有关该附加问题的更多信息 :) 我的意思是,请提供您的完整组件实现
    • 实际上它可以工作,就像你说的那样,我在 fetch 内部使用了 this.props.onQRRead(json[0]) ,而不是 () => this.props.onQRRead(json[0] )。现在它工作得很好。另一个问题...我可以发送更多参数( json[1],json[2]... )吗?如果可以,当我只有 action.payload 时,如何更新减速器中我状态的每个属性?我可以执行 action.payload[1]、action.payload[2] 之类的操作吗?提前发送
    • 请提出另一个问题 :) 我一定会在那里为您提供帮助
    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 2020-10-31
    相关资源
    最近更新 更多