javascript - 类型错误 : Cannot read property 'map' of undefined - how to access an array in a local json API

标签 javascript reactjs

我能够使用 fetch 在本地导入一个 api JSON,该 api 在 this 中可用。 url 如果你想查看它。

问题如下,在传递状态 searchString 时出现以下错误:

'TypeError: Can not read property' map 'of undefined'

我认为这是因为我正在导入完整的 json 对象,而我只需要访问关键结果。

File App.js

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

  componentDidMount() {
    fetch('./recipes.json')
        .then(response => response.json()) 
        .then(json => console.log(json )) 
        .then(json => this.setState({ searchString: json }));
  }

  render() {
    return (
      <div className="App">
        <Navbar />
        <div className="container mt-10">
          <div className="row">
            <RecipeItem list={this.state.searchString}/>
          </div>
        </div>
      </div>
    );
  }
}

File RecipeItem.js 

const RecipeList = ({ searchString }) => {
    <div>
        <img className="card-img-top img-fluid" src={searchString.href} alt={searchString.title} />
        <div className="card-body">
            <h5 className="card-title">{searchString.title}</h5>
            <p className="card-text">
                <strong>Ingredients: </strong>{searchString.ingredients}
            </p>
        </div>
    </div>
}

const RecipeItem = (props) => {
    return (
        <div className="col-sm-3 mt-4">
            <div className="card">
                {props.list.map((searchString, index) =>
                    <RecipeList searchString = {searchString} key={index} />
                )}
            </div>
        </div>
    )
}

最佳答案

RecipeItem 组件在最初安装时没有数据,因为您正在进行提取调用。这就是您收到错误的原因。

如果你有数据,你可以添加一个简单的检查,然后做 map /过滤器/或其他任何事情:

{props.list && props.list.map((searchString, index) =>
   <RecipeList searchString = {searchString} key={index} />
)}

关于javascript - 类型错误 : Cannot read property 'map' of undefined - how to access an array in a local json API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55435475/

相关文章:

javascript - 使用 CSS3 变换使视口(viewport)围绕鼠标单击位置居中

javascript - 如果指定了多个类型和有效负载选项,为什么 Redux Promise 会返回 Unresolved promise ?

css - 在 react 中呈现嵌套表行

reactjs - 如何将 react 上下文 api 与 getDerivedStateFromProps 一起使用?

html - 使用 flex : one left and one right 将两个元素对齐在同一行

javascript - 将 Angular Controller 应用于模板

php - 如何动态替换 jQuery MOBILE 中的过滤器搜索栏?

javascript - 从 node.js 缓冲区中读取精度损失的 int64

php - php 和 javascript cookie 之间的区别

javascript - 如何有效地将数据存储在数组中?