首页 > 解决方案 > ReactJS 无法通过 onClick 重新渲染组件

问题描述

我用 react.js 制作了一个简单的应用程序,每次单击按钮时建议随机放置 问题无法在单击后重新渲染组件 每次单击按钮时如何获取新位置

place.js where fetch API 获取数据

state = { loading: true, person: null };
  async componentDidMount() {
    let Xyurl = "https://cors-anywhere.herokuapp.com/";
    let url =
      "https://wainnakel.com/api/v1/GenerateFS.php?uid=26.2716025,50.2017993&g et_param=value";

    let response = await fetch(Xyurl + url);
    let data = await response.json();
    this.setState({ place: data, loading: false });

  }
  render() {
    return (
      <div>
        <div>
          {this.state.loading || !this.state.place ? (
            <div>loading......</div>
          ) : (
            <div className="PlcseContiner">
              <img alt="description" src= . 
              {this.state.place.image[0]} />
                {this.state.place.name}

        </div>
      </div>
    );

按钮从哪里可以渲染位置的建议

class Suggestion extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false
    };
    this.handleClicked = this.handleClicked.bind(this);
  }
  handleClicked(event) {
    event.preventDefault();
    this.setState({
      visible: true
    });
  }

  generateplace() {
    if (this.state.visible) {
      return <Place />;
    }
    return null;
  }

  render() {
    return (
      <div className="main-button">
        <Button onClick={this.handleClicked} color="warning" className="Btn">
          suggestion
        </Button>
        {this.generateplace()}
      </div>
    );
  }

}

标签: javascriptreactjs

解决方案


您可以从父级控制它,componentWillUpdate 因此您需要向Place组件添加道具

建议:

class Suggestion extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      refresh: 1
    };
    this.handleClicked = this.handleClicked.bind(this);
  }
  handleClicked(event) {
    event.preventDefault();
    this.setState({
      visible: true,
      refresh: this.state.refresh + 1
    });
  }

  generateplace() {
    if (this.state.visible) {
      return <Place refresh={this.state.refresh} />;
    }
    return null;
  }

  render() {
    return (
      <div className="main-button">
        <Button onClick={this.handleClicked} color="warning" className="Btn">
          suggestion
        </Button>
        {this.generateplace()}
      </div>
    );
  }

您需要将操作与如下功能分开:

地方:

componentDidMount() {
    this.getPlace()
}

componentWillUpdate(nextProps, nextState) {
    this.getPlace();
}

getPlace = async() => {
    let Xyurl = "https://cors-anywhere.herokuapp.com/";
    let url =
          "https://wainnakel.com/api/v1/GenerateFS.php?uid=26.2716025,50.2017993&g et_param=value";

    let response = await fetch(Xyurl + url);
    let data = await response.json();
    this.setState({ place: data, loading: false });
}

推荐阅读