ReactJS无法通过onClick重新呈现组件

时间:2019-05-27 18:45:38

标签: javascript reactjs

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

place.js在哪里获取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>
    );
  }

}

1 个答案:

答案 0 :(得分:1)

您可以使用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 });
}