首页 > 解决方案 > React 组件没有在 setState 上重新渲染

问题描述

我有以下代码。我正在使用 setState 方法 ( this.setState({ country: "", offset: "" });) 设置状态,它不会导致render()方法自行重新呈现。

  state = { country: "", offset: "" };
  onClicked = () => {
    console.log("Fine Click away");
    // Get the call back from props
    let country = this.state.country;
    let offset = this.state.offset;
    this.setState({ country: "", offset: "" });
    const callback = this.props.onpress;

    if (callback) {
      callback(country, offset);
    }
  };
getTheCountryName = event => {
    this.setState({ country: event.target.value });
  };
  getTheOffSet = e => {
    this.setState({ offset: e.target.value });
  };
render() {

    const Caption = this.props.caption;
    return (
      <div>
        <br></br>
        <br></br>
        <div>Please enter the name of country and offset:</div>
        <input
          placeholder="Name of Country"
          onChange={this.getTheCountryName}
        />
        <input placeholder="offset" onChange={this.getTheOffSet} />
        <br></br>
        <br></br>
        <button className="rectangular-button" onClick={this.onClicked}>
          <div className="caption">{Caption}</div>
        </button>
      </div>
    );
  }
}```

标签: javascripthtmlcssreactjsjsx

解决方案


以任何方式重置状态都不会触发输入值的更新,因为您实际上并没有在要返回的 JSX 中使用您的状态。下面的代码会将值提供给输入,以便在您的状态更改时更新它们。你可以在这里阅读 React 中的表单和受控输入:

class App extends React.Component {
   state = { country: "", offset: "" };
  onClicked = () => {
    console.log("Fine Click away");
    // Get the call back from props
    let country = this.state.country;
    let offset = this.state.offset;
    this.setState({ country: "", offset: "" });
    const callback = this.props.onpress;

    if (callback) {
      callback(country, offset);
    }
  };
getTheCountryName = event => {
    this.setState({ country: event.target.value });
  };
  getTheOffSet = e => {
    this.setState({ offset: e.target.value });
  };
render() {

    const Caption = this.props.caption;
    return (
      <div>
        <br></br>
        <br></br>
        <div>Please enter the name of country and offset:</div>
        <input
          placeholder="Name of Country"
          onChange={this.getTheCountryName}
          value={this.state.country}
        />
        <input value={this.state.offset} placeholder="offset" onChange={this.getTheOffSet} />
        <br></br>
        <br></br>
        <button className="rectangular-button" onClick={this.onClicked}>
          <div className="caption">Reset</div>
        </button>
      </div>
    );
  }
}


推荐阅读