ReactJS 从父组件的 onClick 方法更新对子组件的 ajax 调用

ReactJS Update ajax call to child component from onClick method from parent

本文关键字:组件 调用 更新 ajax onClick ReactJS 方法      更新时间:2023-09-26

>我有一个从一个json文件传递的数据数组。

当我单击列表项时,它会触发一个handleClick方法,该方法将获取新 url 并将其设置为提供的状态。然后将该状态传递给使用该链接进行 ajax 调用的子组件。

问题是 ajax 调用仅在组件挂载时加载一次,并且无论我单击它多少次,之后都不会再进行调用。

如何让子组件在每次单击不同项目时加载新 URL?

父组件:

getInitialState: function() {
    return {
        gameUrl: ''
    };
},
handleClick: function() {
    this.setState({
        gameUrl: gameUrl
    });
},
render: function() {
    var gameList = this.props.data.map(function(game) {
        var homeTeamName = game.home_team_name;
        var awayTeamName = game.away_team_name;
        var gameUrl = game.game_directory+'/anotherFile.json';
        console.log(homeTeamName+' vs '+awayTeamName+':'+ gameUrl);
        var click = this.handleClick;
        return (
            <li key={game.location} className="list-group-item" onClick={click}>
               {homeTeamName}
            </li>   
        );
    }, bind);
    return (
        <div>
            <ul>
                {gameList}
            </ul>
            <GameDetail url={this.state.gameUrl}/>
        </div>
    );

子组件:

    componentDidMount: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({
            data: data.data
        });
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
},

实现componentWillReceiveProps方法。当道具已更改并且这不是初始渲染时,将调用它。然后根据现有和即将推出的道具更新状态。

componentWillReceiveProps: function(nextProps) {
  this.setState({
    // set something 
  });
}

感谢@WitVault设法做到了,这里是修订的部分:

我没有使用 componentDidMount,而是在子组件中将其更改为 componentWillReceiveProps。确保您通过的道具在子组件和父组件中相同。(即在子组件中 prop 是url的,在父组件中,您将其传递给同一个 prop <GameDetail url={this.state.gameUrl}/>然后,您可以通过nextProps.urlcomponentWillReceiveProps方法中访问它

componentWillReceiveProps: function(nextProps) {
// Access the url prop
var newUrl = nextProps.url;
$.ajax({
  url: newUrl,
  dataType: 'json',
  cache: false,
  success: function(data) {
    this.setState({
        data: data.data
    });
  }.bind(this),
  error: function(xhr, status, err) {
    console.error(this.props.url, status, err.toString());
  }.bind(this)
});
},