ReactJS状态自行重置

时间:2018-11-21 10:40:30

标签: javascript reactjs

我的ReactJS代码出现一个奇怪的问题(对我来说)。 我刚刚开始学习ReactJS,所以我可能做的很愚蠢,但这就是正在发生的事情。

链接到codepen: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()应该调用应该设置this.state.error的getNewJson()。在render()中,它应该console.log("ERROR")这样做,所以很好。但是之后,它将立即再次转到console.log("Waiting")。因此,也许与第一个问题有关,因为状态已重置。

第三个问题,为什么我在80%的情况下会在获取内容时遇到错误?

最奇怪的是,如果我取消注释构造函数中的this.getNewJson(1),所有问题都会消失!

1 个答案:

答案 0 :(得分:0)

我认为的主要问题是onSubmit可以执行您想要的操作,然后重新加载页面以取消请求。为防止这种情况,您需要做的是在调用回调函数后调用e.preventDefault()。

将onSubmit更改为类似的内容应该可以解决主要问题

onSubmit = {(e) => {
    this.props.callback(this.state.value);
    e.preventDefault();
}}

https://codepen.io/anon/pen/QJaeyY

第二,要获取错误信息,应使用.catch()而不是then()中的第二个回调函数,因为这是建议的语法,并且适用于大多数浏览器。

相关问题