【问题标题】:Render object in a select dropdown在选择下拉列表中渲染对象
【发布时间】:2019-06-13 05:42:40
【问题描述】:

我是 react.js 的初学者,我真的需要一些帮助,我正在尝试从 mysql 数据库中获取一些数据到 react.js 中的选择下拉列表中,但数据将在[object, Object] 并且不会加载到选择中。

我的选择下拉列表不是空的,“数据”只是在文本中不可见。即,我的食物对象中有三个项目,在我的选择下拉列表中,我有三个空白项目可供选择,一旦我点击一个“项目”,我会收到错误消息“TypeError:无法读取属性'map '未定义的”。

我已经尝试过 (React selecting option with object as attribut value) 的解决方案,但它不起作用(但这是同样的问题)

我也尝试过使用 JSON.stringify 没有任何成功。非常感谢您的建议!

class Test extends Component {
    constructor(props) {
    super(props);
    this.state = {
        food: []
    };
}

componentDidMount() {
  fetch('/test')
    .then(response => response.json())
    .then(food=> (
      this.setState({food}))
    );
}

 render() {
console.log(this.state);
return <div className="container">
    <div className="selection">
      <Select options={this.state.food} className="dropdown">
      {this.state.food.map((food, index) => (
          <option key={index} value={index}>
            {food.foodName}
          </option>
        ))}
      </Select>
      <div> 

      <p> Listing data from mysql like this works {
        this.state.food.map(food => (
          <li key={food.foodName}>{food.foodName}</li>))}
      </p>
      </div>
    </div>
  </div>
  }
}
 export default Test;

===========================

What I can see in the console (response from the server)

【问题讨论】:

  • 您能否向我们展示一些来自服务器的响应的 JSON 示例?此外,还有几个问题。在您的构造函数中,您是否打算执行this.handleFood = this.handleFood.bind(this)?您没有名为food 的函数。此外,在您的更改函数中,您将 food 的值设置为某个未定义的函数,而不是事件的更改值...
  • 对不起,handleFood-function 不应该在那里。我已经删除了。我添加了一张我从服务器获得的响应的图片。希望对您有所帮助!

标签: reactjs


【解决方案1】:

来自服务器的 JSON 响应是:

{ food: [...] }

但是,当你这样做时:

.then(food => (
  this.setState({ food }))
);

您将状态设置为:

{
  food: {
    food: [...],
  },
},

您需要访问响应中的 food 键并将其设置为 state 中的值:

.then(response => {
  this.setState({ food: response.food });
});

【讨论】:

  • 所以我将 componentDidMount 更改为: componentDidMount() { fetch('/test') .then(response =>{ this.setState({food: response.food} ); });并且由于“无法读取未定义的属性'map'”而导致react-app崩溃我得问,如何在

    中列出json-data而不在

猜你喜欢
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-10
  • 2021-12-13
  • 2018-01-19
  • 1970-01-01
相关资源
最近更新 更多