【问题标题】:Passing state from ajax from one component to another将状态从 ajax 从一个组件传递到另一个组件
【发布时间】:2025-12-19 21:50:18
【问题描述】:

我有一个组件,用户单击按钮转到另一个页面 (localhost:3020 --> localhost:3020/python)。我想使用在App.js 的输入框中输入的 url 向返回 JSON 对象的 Python 脚本发出 ajax 请求,然后将其存储到 posts 数组中。然后我想在单击按钮时将post 数组中的值传递给PythonComponent.js。当我输入 URL 并单击链接时,我的 console.log 语句会显示在控制台中,但我没有看到来自 posts 的任何文本呈现。

如果我在App.js 的状态中创建一个虚拟变量,使用输入框中的文本更新状态,输入框文本将呈现在localhost:3020/python 上。当我在进行 ajax 调用后尝试返回 posts 时,它不起作用。

我的问题是如何将postsApp.js 传递到PythonComponent.js?

App.js

class App extends Component {
    constructor(props) {
    super(props);
    this.state = {
      posts=[]
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick () {
    const urlBox = document.getElementById("box").value;
    this.setState({
      sendText: urlBox,
    })

    $.ajax({
    type: "GET",
    data: { arg1: urlBox} ,
    url: "http://127.0.0.1:5000/hello/",
    }).done(function(res) {
      this.setState({posts:res
      });
      console.log(res.title, res.text)
    }.bind(this));
  }


  render() {
    return (
        <div className="App">
            <div>
            <p className = "input-title"> Enter a URL</p>
            <input placeholder = "placeholder text" id="box" ref="textBox" type="text"/>
            <button onClick={this.handleClick}>
               <Link to={{pathname:"/python", message: this.state.posts.title}}> cant use button have to use link text </Link>
            </button>
          </div>
        </div>
    );
  }
}

export default App;

index.js

 <BrowserRouter>
   <Switch>
     <Route path='/python' component={PythonComponent} />
      <Route path='/' component={App} />
   </Switch>
</BrowserRouter>

PythonComponent.js

class PythonComponent extends Component {
  render() {
    return (
      <div>
        <Link to={{pathname:"/"}}> home </Link>
        <h1> HI </h1>
        {this.props.location.message} 
      </div>
    );
  }
}
export default PythonComponent;

【问题讨论】:

    标签: javascript reactjs components state


    【解决方案1】:

    我注意到的第一件事是您缺少 App 组件的构造函数的一部分。也许只是复制/粘贴错误?

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          posts=[]
        };
        this.handleClick = this.handleClick.bind(this);
      }
      ...
    

    其次,如果 App 仅发出 Ajax 请求以获取 PythonComponent 的数据,我会将该调用移至 PythonComponent 并让它处理请求和渲染周期责任。您可以将该请求放在componentDidMount lifecycle hook 中。一旦请求解决并且您设置了状态,渲染函数将再次触发。

    我建议将请求移至 PythonComponent 的原因是,当用户单击 Link 组件时,它已经在 AJAX 请求解析之前 重定向了用户。因此 PythonComponent 没有可用的数据。通过移动它,重定向发生,PythonComponent 将被挂载,获取它需要的数据,然后在状态更新后重新渲染。

    第三,当您使用Link 将状态传递给链接组件时,您需要使用state 属性。例如:

    <Link to={{
      pathname: '/python',
      state: { message: 'Hello!' }
    }}/>
    

    有关详细信息,请参阅Link documentation

    希望这会有所帮助!

    【讨论】:

      最近更新 更多