【问题标题】:React state is array of objects which are react elements反应状态是反应元素的对象数组
【发布时间】:2018-05-18 12:36:12
【问题描述】:

我现在正在尝试使用 react 呈现列表时遇到问题,我将我的 react 元素保存到状态中,但我遇到的问题是控制台输出以下内容:

未捕获的错误:对象作为 React 子项无效(找到:带有键 {} 的对象)。如果您打算渲染一组子项,请改用数组。

以下是导致错误的状态:

export default class UserData extends Component {
  constructor() {
    super();
    this.state = {
      resultsItems: {}
    }
  };

  componentDidMount() {

    fetch(url)
      .then(results => {
        return results.json();
      }).then(data => {
        console.log(data.items);
        let items = data.items.map((item) => {
          console.log(item.title);
          return (
            <li>
              <h2>item.title</h2>
            </li>
          )
        });

        this.setState({resultsItems: items});
        console.log("state", this.state.resultsItems);
      })
      .catch(error => console.log(error))
  };

  render() {
    return (
      <div>
        <button onClick={() => this.props.updateLoginStatus(false)}>
          Logout
        </button>
        <div>
          ID: {this.props.user}
          {this.state.resultsItems}
        </div>
      </div>
    )
  }
}

【问题讨论】:

  • 除了 Chris 的正确答案之外,请注意 item.title 在您的 componentDidMount 中需要大括号。
  • 顺便说一句,我强烈建议您避免将组件本身存储在状态中,而是存储构建组件所需的可序列化数据。更多详情请见the official advice on the matter
  • @Hamms 非常正确。
  • 虽然有人问过,但这里的答案更完整:Add element to a state React

标签: javascript reactjs jsx


【解决方案1】:

通过演示 Hamms 在他们的评论中谈论的事情:

class UserData extends Component {
  constructor () {
    super()
    this.state = {
      resultsItems: []
    }
  }

  componentDidMount () {
    // Simulate API response
    const resultsItems = [
      { title: 'foo' },
      { title: 'bar' },
      { title: 'wombat' }
    ]
    this.setState({ resultsItems })
  }

  render () {
    return (
      <div>
        {this.state.resultsItems.map(item => <ResultsItem item={item} />)}
      </div>
    )
  }
}

function ResultsItem ({ item }) {
  return <li>{item.title}</li>
}

但是,Chris' 对错误消息原因的回答是正确的:第一次渲染尝试使用空对象而不是数组,但失败了。

【讨论】:

    【解决方案2】:

    您似乎在componentDidMount 上正确地将数组设置为您的状态,但是构造函数中的初始状态 是一个对象而不是数组!

    所以改变这个:

    this.state = {
      resultsItems: {}
    }
    

    到这里:

    this.state = {
      resultsItems: []
    }
    

    【讨论】:

    • 这似乎不起作用。似乎 fetch 内部的 return 语句正在向该数组添加对象,这导致了问题。
    • @KeyferMathewson,您可能需要仔细检查您的 fetch 实际返回的内容。我们无法通过 atm 查看您的 API 返回的内容。
    猜你喜欢
    • 1970-01-01
    • 2021-12-26
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    相关资源
    最近更新 更多