账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    React component 之间传值的问题
    43
    0

    需求:
    现在有两个 component ,一个是 parent,一个是 child,在 parent component 中,我需要发送一个请求获取到数据,然后我需要把数据传递给 child componentchild component 在拿到数据后再去根据传递过来的数据发送请求。

    尝试的方法:
    parent componentcomponentDidMount 方法中发送请求,然后在 render 中把请求的 props 数据传递给 child componentchild componentcomponentDidMount 中在去接收传递过来的数据进行请求数据,结果发现并不能得到想要的结果。原因是:
    parent render 之后,接着 child 就会 render,然后 child componentDidMount 就会被调用,最后才会调用 parent componentDidMount,那么我在 parent 中拿到数据后 re-render,在 child 不会再次调用 componentDidMount了(componentDidMount 只会执行一次)

    请问有其它的方法可以实现这个需求吗?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 一个人的旅行 普通会员 1楼

      在React中,组件之间传递值主要有以下几种方式:

      1. 使用props:props是React组件与父组件之间数据传递的一种方式。父组件通过props向子组件传递数据,子组件再通过props向父组件传递数据。

      ```jsx // 子组件 class Child extends React.Component { constructor(props) { super(props); this.state = { name: 'John' }; }

      render() { return (

      Name: {this.state.name}

      ); } }

      // 父组件 class Parent extends React.Component { render() { return (

      ); } } ```

      1. 使用state:state是React组件自身的数据结构,可以用来存储组件内部的数据。

      ```jsx // 子组件 class Child extends React.Component { constructor(props) { super(props); this.state = { name: 'John' }; }

      render() { return (

      Name: {this.state.name}

      ); } }

      // 父组件 class Parent extends React.Component { render() { return (

      ); } } ```

      1. 使用Context API:Context API可以让你在组件树中传递和接收数据,不需要使用props。

      ```jsx // 子组件 class Child extends React.Component { render() { return (

      Name: {this.state.name}

      ); } }

      // 父组件 class Parent extends React.Component { render() { return (

      ); } }

      class App extends React.Component { state = { childName: 'John' };

      componentDidMount() { this.setState({ childName: 'Doe' }); }

      render() { return (

      ); } } ```

      以上就是React中组件之间传递值的一些常见方式,选择哪种方式主要取决于你的需求和项目的具体情况。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部