javascript - 如何在反应中获取?
问题描述
下午好,我从服务器获取json,我处理它,但是对render的调用发生了2次。谷歌,在构造函数中创建一个空对象。如果对象没有属性,则返回未定义,但我也有数组,应用程序从中崩溃。我附上代码。如何将数据取出状态?是否可以在渲染中获取并写入?
export default class Forma extends React.Component {
constructor(props) {
super(props);
this.state = { data: [] };
}
componentWillMount() {
fetch("http://localhost:3001")
.then(response => response.json())
.then(result => this.setState({ data: result }))
.catch(e => console.log(e));
}
render() {
const { data } = this.state;
return <h1>{console.log(data.goals[0].gs_id)}</h1>; //падает
}
}
解决方案
使用componentDidMount
代替componentWillMount
,它已被弃用。
这是克里斯托弗处理异步操作的答案中一个非常好的补充。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/todos")
.then(response => response.json())
.then(result =>
this.setState({
data: result
})
)
.catch(e => console.log(e));
}
render() {
const { data } = this.state;
return <h1> {data[0] ? data[0].title : 'Loading'} </h1>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
推荐阅读
- c - 自定义排序算法 (C)
- c++ - 对“readimagefile”的未定义引用
- python - 从一列字典中获取一个大字典
- mqtt - AT命令中的转义字符是什么?
- python - 我正在尝试编写 ping n 台服务器并将结果存储在与 ex ping 8.8.8.8 >>c:\result.txt 相同的文本文件中的 python 脚本
- javascript - Django:无法触发 AJAX 调用并将值发送回我的表单
- iframe - 我应该为“SameSite = None”和“Secure”发送什么值?
- c# - 为什么自定义中间件仍在运行?
- python - 在不同的 python 文件中使用 MySQL Flask 连接
- firebase - 如何从数据表中的 Firebase 检查 null?