尝试将 redux 与 react 结合使用

Trying to use redux with react

所以,我有一个 React 应用程序,我在其中使用多个 apis 来获取一些数据,并且我正尝试开始在其中使用 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)
    });


}

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(也称为reducing function)是一个接受累加和值以及returns 新累加的函数。它们用于将一组值缩减为单个值。 https://redux.js.org/glossary#reducer
  • 连接:连接基本上是您的组件从全局状态接收数据的一种方式。输入组件的状态输出。
  • Dispatch:Dispatchers 是您用来输入触摸状态的函数。

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