我的 ReactJS 代码有一个奇怪的(对我来说)问题。 我刚开始学习 ReactJS,所以我可能会做一些非常愚蠢的事情,但这就是正在发生的事情。
代码笔链接:https://codepen.io/Scyleung/pen/XyVovg
我有这样的组件
class LeaseData extends React.Component {
constructor(props) {
super(props);
this.state = {
id: null,
ready: false,
data: null,
error: null,
};
this.update = this.update.bind(this);
//this.getNewJson(1);
}
update(newID) {
this.setState({
id: newID,
ready: false,
data: null,
error:null,
});
console.log("From Main: " + newID + " " + this.state.id);
this.getNewJson(newID);
}
getNewJson(id) {
let url = "https://hiring-task-api.herokuapp.com/v1/leases/"+id;
fetch(url)
.then(res => res.json())
.then(
(result) => {
console.log(result);
this.setState({
ready: true,
data: result
});
},
(error) => {
console.log("Error: " + error.message);
this.setState({
ready: true,
error: error
});
}
)
}
render() {
if (this.state.error) {
console.log("ERROR")
return (
<div>
<Form callback = {this.update}/>
Error: {this.state.error.message}
</div>);
} else if (!this.state.ready) {
console.log("Waiting")
return (<Form callback = {this.update}/>);
} else {
console.log("Displaying")
return (
<div>
<Form callback = {this.update}/>
{this.state.data.rent}</div>
);
}
}
}
我有一个在用户提交表单时调用 update() 的表单。
第一个问题,在 update() 中,console.log() 总是说 this.state.id 为 null,即使在多次提交表单后也是如此。
第二个问题,update()
应该调用getNewJson()
设置this.state.error,如果fetch发生错误.在 render()
中,它应该是 console.log("ERROR")
,它确实如此,所以这很好。但是紧接着它会再次转到 console.log("Waiting")
。所以可能与第一个问题有关,因为状态已重置。
第三个问题,为什么我在 80% 的时间里都会遇到错误?
最奇怪的是,如果我取消注释构造函数中的this.getNewJson(1)
,所有问题都消失了!!
最佳答案
我假设的主要问题是 onSubmit 做了你想要的,但随后重新加载页面取消了请求。您需要做的是在调用回调函数后调用 e.preventDefault() 来防止这种情况。
将您的 onSubmit 更改为这样的内容应该可以解决主要问题
onSubmit = {(e) => {
this.props.callback(this.state.value);
e.preventDefault();
}}
https://codepen.io/anon/pen/QJaeyY
其次,要从 fetch 中获取错误,您应该使用 .catch() 而不是 then() 中的第二个回调函数,因为这是建议的语法并且应该适用于大多数浏览器。
关于javascript - ReactJS 状态重置自己,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53410287/