开发者问题收集

获取状态后返回未定义

2019-01-08
554

我使用 fetch 将数据发布到我的本地 api,但在尝试获取它们时,出现了这样的错误。在 fetch 中,我完全可以得到结果,但之后尝试将其传递到下面的状态:

this.setState({ items: result.items })

but items returns undefined and don't know why ?

我的代码:

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
          items: [],
          error: null,
          isLoaded: false

        };
        this.setState = this.setState.bind(this);
      }

      componentDidMount() {
        fetch("http://localhost:3000/items")
          .then(res => res.json())
          .then(result => {   
                console.log(result);
              this.setState({
                items: result.items,
                isLoaded: true
              });
                console.log(this.state.items)
            },                       
            (error) => {
              this.setState({
                isLoaded: true,
                error
              });
            }
          )
      }


      render() {
        const { error, isLoaded, items } = this.state;
        if (error) {
          return <div>Error: {error.message}</div>;
        } else if (!isLoaded) {
          return <div>Loading...</div>;
        } else {
          return (

            <ul>
                <h1>Saved items:</h1>
              {
                items && items.map(item => (
                    <li key={item.name}>
                       item: {item.name} {item.price}
                    </li>
                ))
            }
            </ul>
          );
        }
      }
}
1个回答

您可以执行下列操作:

this.setState({
    items: result.items || [],
     isLoaded: true
});

{
    items && items.map(item => (
        <li key={item.name}>
            {item.name} {item.price}
        </li>
    ))
}
GreenTeaCake
2019-01-08