【问题标题】:Show new state of attribute for each listitem显示每个列表项的新属性状态
【发布时间】:2018-10-21 14:31:25
【问题描述】:

我正在 React 中呈现属性(艺术家)列表。在呈现时,必须为每个列表项发出单独的 HTTP 请求以显示附加信息(流派)。为了解决这个问题,我预先在 state 中放置了一个空数组——在渲染过程中为每个 item 更新这个 state:

let newState = Object.assign({}, this.state);
          newState.categoryList[item.id] = names; // names is a single string containing all genres
          this.setState(newState);

最终,在调用 JSX:{this._getCategories(item)} 中的方法后,我试图在文本字段中显示流派(放入单个字符串中)。

/* this._getCategories is called to make an additional HTTP request for
         every item in the list. this.state.categoryList[item.id] should contain
         the required value (string). */
        {this._getCategories(item)}
        <Text style={styles.categories}>this.state.categoryList[item.id]</Text>

我在 Expo.io 上制作了一个可复制的版本,可以在这里找到:Snippet。为了让事情更容易理解,我在代码的每一部分都添加了额外的 cmets。

编辑

问题似乎是我用来更新状态的方式,导致预期值不可见。接受的答案帮助我解决了这个问题。

【问题讨论】:

  • 每当您基于现有状态设置新状态时(如在您的第一个代码块中),您必须使用setState 的回调版本及其状态对象路过你;你不能像上面那样做。更多:reactjs.org/docs/… 这实际上可能是问题所在,如果问题是您没有看到更新。但是你还没有告诉我们问题是什么。 :-) 你已经描述了一种情况,但没有说什么(如果有的话)没有按照你的意愿行事......?
  • 请使用 Stack Snippets([&lt;&gt;] 工具栏按钮)将您的可运行 minimal reproducible examplein 放入问题中,以便回答问题所需的所有代码都是 在问题中。 Stack Snippets 支持 React,包括 JSX; here's how to do one.

标签: javascript reactjs react-native get


【解决方案1】:

如果您遇到的问题是当您的 HTTP 请求完成时您没有看到重新渲染的内容,那是因为您在这里违反了 React 规则:

// Incorrect
let newState = Object.assign({}, this.state);
newState.categoryList[item.id] = names; // names is a single string containing all genres
this.setState(newState);

每当您基于现有状态设置新状态时(如在您的第一个代码块中),您必须使用setState 的回调版本及其传递给您的状态对象;你不能像上面那样做; docs.

你说过categoryList 是一个数组。根据您的描述,它听起来像是一个 sparse 数组(至少最初是这样)。设置状态时,必须复制包含更改的数组,不能直接修改它。由于它看起来很稀疏,我们不能按照通常的方式(在文字中使用扩展符号)来做,我们必须使用 Object.assign 来代替:

// Correct
this.setState(({categoryList}) => ({categoryList: Object.assign([], categoryList, {[item.id]: names})}));

或可能更清晰、更详细的版本:

this.setState(state => {
    const categoryList = Object.assign([], state.categoryList);
    categoryList[item.id] = names;
    return {categoryList};
});

【讨论】:

  • 这太好了,非常感谢您提供的所有提示和有用的回答!目前它运行良好。干杯:)
猜你喜欢
  • 1970-01-01
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
相关资源
最近更新 更多