【问题标题】:Object array implementation in reactJS storereactJS store 中的对象数组实现
【发布时间】:2019-06-17 15:25:12
【问题描述】:

我知道如何使用 reactJS store,但是当我将 store 与对象数组一起使用时遇到了问题。

    constructor(props) {
      super(props);
      this.state = {
        array: [{ id: null, summary: "", name: "" }]
      };
    }

componentWillMount() {
  const query = "http://api.tvmaze.com/search/shows?q=game";
  var dataCount;
  axios.get(query).then(response => {
    dataCount = response.data.length;
  });

  axios.get(query).then(response => {
    for (let i = 0; i < dataCount; i++) {

      if (response.status) {
        this.setState({
          array: [
            ...this.state.array,
            {
              id: i,
              summary: response.data[i].show.summary,
              name: response.data[i].show.name
            }
          ]
        });
      }
    }
  });
}

实际上,我确实编写了此代码,但存在很多问题。它是 在 this.state.array[0] 中存储 array[0] 8-9 次。当我写 console.log(this.state.array[0]) 它不只打印一个实例。 始终打印有关 axios GET 方法响应计数次数的对象。 我想存储像 this.state.array[0]={id:1, summary:"xyz",name:"abc"}, this.state.array1={id:1, summary:"xyz", name:" abc"}。

【问题讨论】:

  • 为什么要发送两个axios请求?
  • 一个是获取数据计数,另一个是使用 for 循环获取数据。但你是对的,一个就足够了
  • 您不必对两个请求执行此操作。它们都是异步运行的,所以不能保证在解析第二个时,dataCount 的值不是 undefined。把它们放在一起。

标签: reactjs react-native store


【解决方案1】:
  1. 这里不需要发送两个请求。您可以在一个请求中获取数据和数据长度并使用它们。这样实际上会更好,因为 axios 请求不会按顺序解析,所以在代码循环时您可能并不总是有长度。
  2. 可以为状态中的数组使用更好的名称,例如shows
  3. 里面有一个初始的空项目,似乎没有理由,可能会扔掉它。
  4. 将获取的数据直接存储到状态中可能更直接,而不是像这样从中提取特定的键,但这是次要的。
  5. 使用componentDidMountcomponentWillMount is deprecated.

See this demo

【讨论】:

  • 是的,但我想编写函数以使用对象的属性作为函数参数来应用字符串解析等函数并从段落中获取单词并在其他地方使用它们。这样一来,我就非常沉迷于那个响应数据映射。它不太适合 react 的 store 逻辑。 this.state.shows 是空的。
猜你喜欢
  • 1970-01-01
  • 2016-05-12
  • 2020-03-10
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 2016-11-26
相关资源
最近更新 更多