首页 > 解决方案 > componentDidMount() 中的 fetch 问题

问题描述

当我尝试 console.log 时,我的用户列表未定义。也许我没有得到什么?

我想从我工作的 api 中获取我的用户列表(用邮递员测试)并将其放入控制台接下来我想映射我的用户以在应用程序上显示它

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

  componentDidMount() {
    console.log("component did mount");
    fetch("/user/list")
    .then(res => {
      return res.json();
    })
    .then(users => 
      this.setState({users}, () => 
      console.log("list of users => " + users)));
  }

  render() {
    return (
    <div className="form">
      <ul>
        {this.state.users.map((user) =>
          <li key="user._id">{ user.name }</li>
        )}
      </ul>
    </div>
    );
  }
} export default Test;

感谢帮助 !

标签: reactjs

解决方案


您必须退回res.json()才能在下一个使用它.then()

.then(res => {
    res.json();
})

应该

.then(res => 
    res.json();
)

或者

.then(res => {
    return res.json();
})

https://javascript.info/promise-chaining


推荐阅读