reactjs - 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;
感谢帮助 !
解决方案
您必须退回res.json()
才能在下一个使用它.then()
.then(res => {
res.json();
})
应该
.then(res =>
res.json();
)
或者
.then(res => {
return res.json();
})
推荐阅读
- routing - 有没有办法创建一个仅包含路由及其在 Rocket 中的功能的中央路由文件?
- java - 在 oracle 瘦驱动支持的 tnsnames.ora 中声明多个相同的服务
- django - django restframework token 导致 ImportError
- angularjs - 不加载 karma-jasmine 框架中生成的测试用例
- sql-server - 在基础查询中使用 REPLACE 打开 TClientDataSet 时内存不足
- dart - SlickDart 组件使用 AngularDart 错误
- json - 序列化外部节点模块的 JSON 返回到 KotlinJS 中的 Kotlin 类
- javascript - 在 Node.js 中运行函数
- javascript - 在javascript中一次合并2个动态数组1个元素
- r - 无法安装 TinyTeX 包