Javascript 如何在react js中将值从一个组件传递到另一个组件

Javascript 如何在react js中将值从一个组件传递到另一个组件,javascript,reactjs,properties,Javascript,Reactjs,Properties,我有一个组件,其中有一个按钮,我正在调用该组件上的一个节点js服务。我将从该服务获得一个响应,我希望将该响应传递给下一个组件,以便在那里显示数据。下面是我的组件,它正在执行节点js调用 import { FormGroup } from "react-bootstrap"; import "bootstrap/dist/css/bootstrap.css"; import axios from "axios"; export default class Abc extends React.C

我有一个组件,其中有一个按钮,我正在调用该组件上的一个节点js服务。我将从该服务获得一个响应,我希望将该响应传递给下一个组件,以便在那里显示数据。下面是我的组件,它正在执行节点js调用

import { FormGroup } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.css";
import axios from "axios";


export default class Abc extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {}
        }
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick = (e) => {
        e.preventDefault();
        axios.get(url)
            .then(res => {
                this.setState({
                    data: res.data// I need this variable to pass to next component Pqr where I can use it for display purpose.
                })
                this.props.history.push("/Pqr",{ response:res.data});
            })
    };

    render() {

        return (
            <form >
                <button className="btn btn-info btn-sm" onClick={this.handleClick} style={{ whitespace: 'nowrap' }} >
                    Launch
                    </button>
            </form>
        )

    }
}


My Pqr component code is as below.

import React from "react";

export default class ModelLaunch extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
        }
    }
    render() {
        const state = this.props.location.state
        return (
        <h1>This page will display model Inputs : {state} </h1>
        )
    }
}
从“react bootstrap”导入{FormGroup};
导入“bootstrap/dist/css/bootstrap.css”;
从“axios”导入axios;
导出默认类Abc扩展React.Component{
建造师(道具){
超级(道具);
此.state={
数据:{}
}
this.handleClick=this.handleClick.bind(this);
}
handleClick=(e)=>{
e、 预防默认值();
获取(url)
。然后(res=>{
这是我的国家({
data:res.data//I需要将此变量传递到下一个组件Pqr,在那里我可以使用它进行显示。
})
this.props.history.push(“/Pqr”,{response:res.data});
})
};
render(){
返回(
发射
)
}
}
我的Pqr部件代码如下所示。
从“React”导入React;
导出默认类ModelLaunch扩展React.Component{
建造师(道具){
超级(道具);
此.state={
}
}
render(){
const state=this.props.location.state
返回(
此页面将显示模型输入:{state}
)
}
}

我看到您正在更改路由(使用react路由器?)

请记住,
this.setState
是异步的,并且特定于您的组件,当您调用
this.props.history.push('/Pqr')
时,可能还没有更新
this.state.data

要在同一个react项目中通过不同的
路线
共享此数据,我实际上知道您可以:

  • 将其存储在
    窗口。localStorage
    上,然后进入下一条路线

  • 使用(如果不重新加载页面)

  • 使用react路由器通过路由发送数据

如果不是这样,并且您只想将属性向下或向上传递到层次结构树,除了上面的注释之外,也许它可以帮助您:

您可能知道,react项目由以特定方式组合在一起工作的组件组成。在下面的示例中,有两个组件(父亲和孩子)

这样,当
This.state.data
更改时,
virtualComponent
将使用新的
data
值重新呈现

但是,您可能需要反向操作,并且需要将
this.state.data
传递到
Abc
上方的组件,当按下按钮时,该组件在此处列出

要实现这一点,您需要为您的
Abc
设置一个“父”组件,“父”组件必须提供一个
onDataChanged
回调以捕获事件。此回调将接收
数据
,并对其进行处理

在本例中,我将创建另一个组件作为您的
Abc
上面的组件。我给它起个名字<代码>以上ABC组件,完美

...

class AboveAbcComponent extends React.Component {
  constructor(props) {
    this.state = {
      dataFromChild: null
    };

    this.onDataChanged = this.onDataChanged.bind(this);
  }

  onDataChanged(dataReceived) {
    console.log("Yey! It works!");
    this.setState({ dataFromChild: dataReceived });
  }

  render() {// Just the passed props changes here
    ...
      <Abc 
        onDataChanged={this.onDataChanged}
      />
    ...
  }
}

export default class Abc extends React.Component {
  constructor(props) { ... } // No changes here

  handleClick = (e) => {
    e.preventDefault();
    axios.get(url)
      .then(res => {
        this.setState({
          data: res.data
        });

        this.props.onDataChanged(res.data);

        this.props.history.push("/Pqr"); // I really didn't understand Why this push is here... but ok
      })
  };

  render() { ... } // No changes here
}
。。。
类AbcComponent扩展了React.Component{
建造师(道具){
此.state={
dataFromChild:null
};
this.ondatachange=this.ondatachange.bind(this);
}
onDataChanged(数据已接收){
log(“是的!它工作了!”);
this.setState({dataFromChild:dataReceived});
}
render(){//此处仅传递的道具更改
...
...
}
}
导出默认类Abc扩展React.Component{
构造函数(props){…}//此处无更改
handleClick=(e)=>{
e、 预防默认值();
获取(url)
。然后(res=>{
这是我的国家({
数据:res.data
});
此.props.onDataChanged(res.data);
this.props.history.push(“/Pqr”);//我真的不明白为什么会有这样的推送……但还好
})
};
render(){…}//此处无更改
}

希望它有帮助,玩得开心

我用另一种方法解决了上述问题。我没有在Abc组件上调用node js服务,而是将其重定向到新组件,并在新组件的componentDidMount()方法中调用node js服务并在props中存储数据。这样我就有了新公司的数据。下面是我现在在Abc组件中更新的代码

从“react bootstrap”导入{FormGroup};
导入“bootstrap/dist/css/bootstrap.css”;
从“axios”导入axios;
导出默认类Abc扩展React.Component{
建造师(道具){
超级(道具);
此.state={
数据:{}
}
this.handleClick=this.handleClick.bind(this);
}
handleClick=(e)=>{
e、 预防默认值();
这个.props.history.push(“/Pqr”);
})
};
render(){
返回(
发射
)

}
这可能会帮助您这里只有一个组件。如果只是使用组件中声明的状态,则需要一个子组件来传递此数据。@JoeLloyd我还添加了我的Pqr组件代码。我仍然无法访问数据。但他们没有任何关系。如果接收器不是子级,则无法发送在组件中声明的数据。如果您需要这样做,您应该实现contextHook,或者更好的方法是ReduxIt太大了,无法在评论中使用。阅读hooks文档并了解react状态管理。您需要了解这两个基本原则,除了适当的状态管理之外,这个问题没有简单的解决方法。我浏览了上面的链接,但仍然不清楚如何在代码中实现它。
  render() {
    return (
      <form >
        <button 
          className="btn btn-info btn-sm" 
          onClick={this.handleClick} 
          style={{ whitespace: 'nowrap' }} 
        >
          Launch
          <FictionalComponent data={this.state.data} />
        </button>
      </form>
    )
  }
...

class AboveAbcComponent extends React.Component {
  constructor(props) {
    this.state = {
      dataFromChild: null
    };

    this.onDataChanged = this.onDataChanged.bind(this);
  }

  onDataChanged(dataReceived) {
    console.log("Yey! It works!");
    this.setState({ dataFromChild: dataReceived });
  }

  render() {// Just the passed props changes here
    ...
      <Abc 
        onDataChanged={this.onDataChanged}
      />
    ...
  }
}

export default class Abc extends React.Component {
  constructor(props) { ... } // No changes here

  handleClick = (e) => {
    e.preventDefault();
    axios.get(url)
      .then(res => {
        this.setState({
          data: res.data
        });

        this.props.onDataChanged(res.data);

        this.props.history.push("/Pqr"); // I really didn't understand Why this push is here... but ok
      })
  };

  render() { ... } // No changes here
}