在选择下拉列表中渲染对象

时间:2019-01-18 23:40:32

标签: reactjs

我是react.js的完整入门者,我确实需要一些帮助,我正在尝试从mysql数据库中获取一些数据到react.js中的select-下拉列表中,但这些数据将保存在[object,Object]并且不会加载到选择中。

尽管我的选择下拉列表不为空,但是“ data”在文本中不可见。即,我的食物对象中有三个项目,在选择下拉菜单中有三个空白项目可供选择,单击“项目”后,我收到一条错误消息,提示“ TypeError:无法读取属性'map 'of undefined”。

我已经尝试过(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)

1 个答案:

答案 0 :(得分:0)

您从服务器获得的JSON响应是:

#!/usr/bin/env python3

text_list = [["hello", "how", "are", "you", "fine", "thank", "you"],
             ["good", "morning", "have", "great", "breakfast"],
             ["you", "are", "a", "student", "I", "am", "a", "teacher"],
             ["trump", "it", "is", "a", "fake", "news"],
             ["obama", "yes", "we", "can"]]

# use a set() for remove words because testing for inclusion is much faster than a long list
# removed two of your original bad words so I could make sure it passed some
remove_words = set(["hello", "breakfast", "obama"])

#make a generator, rather than a list, because why not?
result = (sentence for sentence in text_list if all(word not in remove_words for word in sentence))

for acceptable in result:
    print(acceptable)

但是,当您这样做时:

{ food: [...] }

您将状态设置为:

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

您需要访问响应中的{ food: { food: [...], }, }, 键,并将其设置为状态值:

food