【问题标题】:Objects are not valid as a React child when trying to map data from my api尝试从我的 api 映射数据时,对象作为 React 子项无效
【发布时间】:2021-03-21 08:48:33
【问题描述】:

我收到了错误

错误:对象作为 React 子对象无效(找到:带键的对象 {id, recipe_dificulty, recipe_id, recipe_name, recipe_steps})

我正在使用 Axios 来获取我的数据,这里是提供给我的 react 项目的数据。

https://pastebin.com/ydNrFLBW(此处信息太多,无法发布)

这是我第一次使用信息的 Mealplans 课程。

export default class Mealplans extends Component {   constructor(props) {
      super(props)

      this.state = {
          mealplanItems: []
      }   }

  componentDidMount() {
    axios.get('http://localhost:5000/all-mealplans'
    ).then(response => {
      console.log(response)
      this.setState({
        mealplanItems: this.state.mealplanItems.concat(
          response.data["mealplans"])
      })
    }).catch(error => {
      console.log("ERROR!", error)
    })   }

  render() {
    const mealplanRecords = this.state.mealplanItems.map(mealplanItem => {
      return <MealplanItem mealplanItem={mealplanItem} />
    })
      return (
          <div>
            <div className="mealplan-page-header">
              <h1>Newest Mealplans</h1>
              <hr />
            </div>
              <div className="content-container">
                {mealplanRecords}
              </div> 
          </div>
      )   } }

【问题讨论】:

  • 你的MealplanItem 是什么?你能告诉我们你的那个组件的代码吗?

标签: reactjs object axios


【解决方案1】:

我的猜测是,mealplanItem 是MealplanItem 中的{object}({id, recipe_dificulty, recipe_id, recipe_name, recipe_steps}),它正在按原样打印。

React 不打印对象。

MealplanItem

//for example...

<div>
  <span>{mealplanItem.id}</span>
</div>

这样试试吧。

【讨论】:

    猜你喜欢
    • 2020-04-04
    • 2021-06-03
    • 2018-06-02
    • 2022-01-10
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 2021-06-04
    相关资源
    最近更新 更多