【问题标题】:Trying to use redux with react [closed]尝试将redux与react一起使用[关闭]
【发布时间】:2019-02-13 20:08:15
【问题描述】:

所以,我有一个 react 应用程序,我在其中使用多个 api 来获取一些数据,并且我正在尝试在其中开始使用 redux。我已经看过一些 redux 教程,但是当我开始考虑如何将这个 react 应用程序转换为 react-redux 时,我仍然有点困惑。就像如何将我使用的(this.setState)这样的东西转换为redux。我知道我必须使用 react-thunk 来开始在操作中获取这个 api,但我仍然很困惑。这是我的代码。

componentDidMount(){

  let url = ``;
  let url2 = ``;



    fetch(url,{
      method: 'GET'
    })
    .then((response)=> response.json())
    .then((responseJson) => {
      const newItems = responseJson.items.map(i => {
        return{
          name: i.name
        };
      })
      const newState = Object.assign({}, this.state, {
        items: newItems
      });

      console.log(newState);
      this.setState(newState);
    })
    .catch((error) => {
      console.log(error)
    });
    fetch(url2,{
      method: 'GET'
    })
    .then((response)=> response.json())
    .then((responseJson) => {
      const newItems = responseJson.item.map(i => {
        return{
          img: i.img.url
        };
      })
      const newarr = [...this.state.items, ...newItems];
      var resObj = newarr.reduce(function(res, obj) {
          for(var key in obj) {
              if (obj.hasOwnProperty(key)) {
                  res[key] = obj[key];
              }
          }
          return res;
      }, {});

      const newState = {
        items: [resObj]
      }

      this.setState(newState);
    })
    .catch((error) => {
      console.log(error)
    });


}

【问题讨论】:

  • 您的具体问题是什么?

标签: reactjs api redux react-redux fetch-api


【解决方案1】:

https://redux.js.org/faq/codestructure

Redux 一开始可能很吓人

你想知道的第一件事不要使用this.setState,至少现在还没有。

这里是redux和react的结构

为简单起见,您只需要了解 Dispatchers、Connect、Action 和 Reducers。

  • 动作:动作是一个简单的对象,表示改变状态的意图。操作是将数据导入存储的唯一方法。任何数据,无论是来自 UI 事件、网络回调还是 WebSockets 等其他来源,最终都需要作为操作进行分派。https://redux.js.org/glossary#action
  • Reducer:reducer(也称为归约函数)是一个接受累加和值并返回新累加的函数。它们用于将值的集合减少为单个值。 https://redux.js.org/glossary#reducer
  • 连接:连接基本上是您的组件从全局状态接收数据的一种方式。输入到您的组件的状态的输出。
  • Dispatch:Dispatcher 是用于输入以触摸状态的函数。

在任何你想使用this.setState 的地方,你都想使用与动作对话的调度(动作描述和定义调度函数。这就是redux-thunk 与fetch 函数发挥作用的地方)。在 dispatch 调用 action 并且 action 从服务器拉取数据后,reducers 清理数据并将其发送回全局存储状态,在该状态下使用 connect 命令,react 拾取。

【讨论】:

    猜你喜欢
    • 2019-02-05
    • 2017-12-09
    • 2018-12-05
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多