为什么使用 props 时函数参数 returns 未定义?

Why the function argument returns undefined when using props?

我正在使用 react-native 构建应用程序。我有 3 个组件,即 Ind.jsButtons.jsRain.js。我需要select一个Rain的选项,并保存在Ind的状态,以便进一步处理。由于 Rain 组件与 Ind 没有直接关系,而是通过 Buttons 中的 navigation route 连接。 我正在使用 react-navigation

为此,我在 Ind 中创建了一个函数 onSelect(),它执行 setState 并通过 props 将其传递给 Buttons,然后再次传递给 Rain 然后我执行了函数,问题是函数被调用但没有传递参数,即 console.logs null 然后 undefined.

我已经尝试 console.log 传递给 Ind 的参数。

Ind.js

export default class Ind extends Component {
constructor(){
super();
this.state = { report: null}
}
onSelect = (newreport) => {
      this.setState({
        report: newreport
      })
      console.log("Parameter: ", newreport)
      console.log("State: ", this.state.report)
    }

render(){
return(
<Buttons selectReport={() => this.onSelect()}
)

}

}

Buttons.js

export default class Buttons extends Component{
constructor(props){
super(props);
}
render(){
return(
<TouchableOpacity
    onPress={() => {this.props.navigation.navigate('Rain',{
                  selectReport: this.props.selectReport });
                }}>
          <Text style={styles.text}>Rain</Text>
 </TouchableOpacity>
)
}
}

Rain.js

export default class Rain extends Component{
constructor(props){
super(props);
this.state = {
selection: "Test"
}
this.selectOption = this.selectOption.bind(this);
}
selectOption = () => {
this.props.navigation.state.params.selectReport(this.state.selection)
}
}

console logreturn先Parameter: undefined State: null可以理解,因为没有点击但是点击后显示 Parameter: undefined State: undefined。 怎么了?我是初学者,绑定或发送道具有什么问题吗? 请解释。

setState 是异步函数,所以这就是为什么在第一次点击后你得到 null(因为它还没有改变)但是你的代码中某处传递 newreport 的值是错误的。

您没有在点击按钮中放置任何parameters。但是,该函数正在接收 parameters 作为值。当然是指向undefind.

onSelect = (newreport) => {
      this.setState({
        report: newreport
      })
      console.log("Parameter: ", newreport)
      console.log("State: ", this.state.report)
    return this.state.report;
    }

render(){
return(
<Buttons selectReport={this.onSelect("value")}
)

使用箭头函数时,需要这样调用,

<Buttons selectReport={() => this.onSelect} > //without parenthesis

另外 setStateasync 所以你需要在 setState 中使用 callback 来打印值。

你需要这样做,

export default class Ind extends Component {
  constructor(){
   super();
   this.state = { report: null}
  }
  onSelect = (newreport) => {
      console.log("Parameter: ", newreport)
      this.setState({
        report: newreport
      },()=> console.log("State: ", this.state.report)) //prints in callback
  }

  render(){
   return(
    <Buttons selectReport={() => this.onSelect}>
   )
  }
}