从帖子数据获取ID反应

时间:2019-07-11 03:22:20

标签: reactjs

我想在提交后立即重定向到创建的元素。到目前为止,我有以下代码:

class Person extends Component {
  constructor(props) {
    super(props);
    this.state = {
      personID: 0,
      description: "",
      phone: ""
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.modifyPersonID = this.modifyPersonID .bind(this);
  }

  handleInputChange(event) {
    const target = event.target;

    const value = target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  modifyPersonID(idx) {
    this.setState({ personID: idx });
    var ruta = "/persons/" + idx + "/";
    return <Redirect to={ruta} />;
  }

  fetchData(event) {
    let idx = "";
    event.preventDefault();
    const body= {
      description: event.target.elements.descripcion.value,
      phone: event.target.elements.phone.value
    };
    fetch("http://api/", {
      method: "post",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body)
    })
      .then(function(response) {
        return response.json();
      })
      .then(function(data) {
        idx = data.id;
      });
    return idx;
  }

  handleSubmit(event) {
    let ruta = "/persons/";
    event.preventDefault();
    let id = this.fetchearData(event);
    this.setState({ personID: id });
    this.modifyID(id);
  }
}

当我尝试重定向到/ persons /:id时,将在重定向到/ persons /:id后执行id的setState命令,因此它将重定向到/ persons / 0。在post语句返回ID后如何立即设置状态?

3 个答案:

答案 0 :(得分:1)

考虑在您的fetchData方法中返回一个Promise而不是ID。如果这不适合您,您可以尝试使用await

答案 1 :(得分:1)

this.setState使用回调函数作为第二个参数。

  modifyPersonID(idx) {
    this.setState({ personID: idx },()=>{
      var ruta = "/persons/" + idx + "/";
      return <Redirect to={ruta} />;
    });
  }

按如下所示设置状态后尝试调用返回。

答案 2 :(得分:0)

要在setState之后调用某个函数,必须使用callback in setState

还使用async/await进行API调用,

async handleSubmit(event) {
    let ruta = "/persons/"; //Remove this line 
    event.preventDefault();
    let id = await this.fetchearData(event);
    this.setState({ personID: id }, ()=> <Redirect to={`/person/${id}`} />); 
    this.modifyID(id); //Remove this line and modifyID function as well
  }