Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在React中用api数据填充下拉列表?_Reactjs - Fatal编程技术网

Reactjs 如何在React中用api数据填充下拉列表?

Reactjs 如何在React中用api数据填充下拉列表?,reactjs,Reactjs,我试图用API中的所有标题填充下拉列表的选项 我正试图: 将标题保存到titles:[]对象中 将所有这些标题映射到单独的元素中 但我得到了错误 未处理的拒绝(TypeError):无法将未定义或null转换为 反对 谁能给我指一下正确的方向吗 import React from "react" import Header from "./Header" import CardContent from "./CardContent&q

我试图用API中的所有标题填充下拉列表的选项

我正试图:

  • 将标题保存到titles:[]对象中
  • 将所有这些标题映射到单独的元素中
但我得到了错误

未处理的拒绝(TypeError):无法将未定义或null转换为 反对

谁能给我指一下正确的方向吗

    import React from "react"
import Header from "./Header"
import CardContent from "./CardContent"
import axios from "axios";

class CardContainer extends React.Component {
  state = {
    display: [],
    titles: []
  };

  componentWillMount = (e) => {
    axios.get("https://ghibliapi.herokuapp.com/films")
      .then(response => this.setState({
        titles: response.data[Object.keys(response.data.title)],
        display: response.data[Math.floor(Math.random() * response.data.length)]
      }))
  }

  render() {
    return (
      <div className="container">
        <Header />
        <select>
          {this.state.titles.map(title => (
            <option key={title} value={title}>
              {title}
            </option>
          ))}
        </select>    
从“React”导入React
从“/Header”导入标题
从“/CardContent”导入CardContent
从“axios”导入axios;
类CardContainer扩展了React.Component{
状态={
显示:[],
标题:[]
};
组件将安装=(e)=>{
axios.get(“https://ghibliapi.herokuapp.com/films")
.then(response=>this.setState({
标题:response.data[对象.键(response.data.title)],
显示:response.data[Math.floor(Math.random()*response.data.length)]
}))
}
render(){
返回(
{this.state.titles.map(title=>(
{title}
))}

您确实应该使用
componentDidMount
来获取数据,但主要问题是您似乎需要一个包含所有标题的数组,因此需要映射响应数据并创建此数组

componentDidMount = (e) => {
  axios.get("https://ghibliapi.herokuapp.com/films").then((response) =>
    this.setState({
      titles: response.data.map(({ title }) => title), // <-- map titles
      display: response.data[Math.floor(Math.random() * response.data.length)]
    })
  );
};
componentDidMount=(e)=>{
axios.get(“https://ghibliapi.herokuapp.com/films)然后((回应)=>
这是我的国家({

titles:response.data.map(({title}=>title),//您得到的错误是“未处理的拒绝(TypeError):无法将未定义或null转换为对象”,因为response.data是数组。object.key()只能应用于对象。Try map()函数逐个提取对象。

当前,this.state.display正在随机抽取标题、描述等,并将它们显示在表格等的页面上。有一个按钮执行handleChange()并将this.state.display重新更新为随机电影。我计划在“选择”下拉列表中设置另一个事件侦听器,以将this.state.display更新为所选电影。@esvnt啊,kk。正如我所说,我只是从片段中猜测。祝你好运。