如何正确地将状态作为道具从一个组件传递到另一个组件? [英] How can I correctly pass state as props from one component to another?

查看:38
本文介绍了如何正确地将状态作为道具从一个组件传递到另一个组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将我的状态作为 props 从组件 Locatione.js 传递到 Map.js,因此当我在 Map.js 中调用函数 SendLocation 时,这些 props 可用.

I'm trying to pass my state as props from component Locatione.js to Map.js, so the props are available when I call the function SendLocation in Map.js.

这是我的组件 Locatione

Here is my component Locatione

export default class Locatione extends Component {
  state = {
    location: null
  };

  componentDidMount() {
    this._getLocationAsync();
  }

  _getLocationAsync = async () => {
    let location = await Location.getCurrentPositionAsync({ });
    this.setState({ location });
    console.log("log this pls", this.state); // the state here logs correctly
  };

  render() {
    return (
      <Map locatione={this.state} /> // when accesing this props in Map, I'm getting **null**
    );
  }
}

这是我的 Map.js 组件

Here is my Map.js component

export default class Map extends React.Component {
  sendLocation() {
    console.log("sending location log", this.props); // the props here appear as null
  }

  render() {
    return (
      <Button
        title="Send Sonar"
        onPress={(this.sendLocation, () => console.log("hi", this.props))} //the props here log correctly
      />
    );
  }
}

我也尝试过以这种方式传递我的道具,但无济于事.

I also tried passing my props in this fashion, to no avail.

export default class Map extends React.Component {

  sendLocation(altitude, longitude) {
    console.log("sending location log", this.props);
  }

  render() {
    return (
      <Button
        title="Send Sonar"
        onPress={(this.sendLocation, (this.props)))}
      />
    );
  }
}

感谢您的帮助

推荐答案

这里有一个小问题:

        onPress={(this.sendLocation, () => console.log("hi", this.props))}

每次代码呈现或重新呈现按钮时,console.log 都会触发,而不是在您单击它时触发.

The console.log will trigger everytime the code renders or re-renders the button, not when you click it.

如果您想在调用函数后登录,请将 onPress 更改为:

If you want to log after you call a function change the onPress to:

        onPress={() => {
                 this.sendLocation()
                 console.log("hi", this.props)
                }}

另一个问题是您没有让 sendLocation 函数访问 this.

The other problem is that you are not giving your sendLocation function access to this.

你有两种方法:

第一种方法:在构造函数中绑定它.所以在你的 Map.js 中添加它:

First way: Binding it inside your constructor. So inside your Map.js you add it like:

constructor(props){
   super(props);
   this.sendLocation.bind(this);
}

第二种方式:将 sendLocation 函数声明为箭头函数:

Second way: Declaring your sendLocation function as an arrow function:

  sendLocation = () => {
    console.log("sending location log", this.props);
  }

这篇关于如何正确地将状态作为道具从一个组件传递到另一个组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆