【问题标题】:Trouble passing props to componentDidMount in child component (React)无法将道具传递给子组件中的 componentDidMount (React)
【发布时间】:2018-07-06 13:11:44
【问题描述】:

我在我的React 应用程序的子组件中将道具传递给componentDidMount() 调用时遇到问题。

在我的App.js 中,我通过Router 传递道具,如下所示:

App.js

class App extends Component {

state = {
    city: ""
}

componentDidMount() {
    this.setState({city: this.props.city});
}

render() {

    return (
        <div>
            <Route path="/" exact render = {() => <Projections city={this.state.city} />} />
            <Route path="/:id" component={FullPage} />
        </div>
    );
}

}

在我的 Projections.js 中,我有以下内容:

Projections.js

constructor(props) {
        super(props);
           this.state = {
            location: this.props.city
        }
    }

    componentDidMount () {
        console.log(this.state.location);
console.log(this.props.city);

    }

console.log(this.state);' returns an empty string.console.log(this.props.city);` 也会返回一个空字符串。

但我需要访问componentDidMount() 中的city 属性的值。 console.log(this.props.city);render() 内返回道具,但不在 componentDidMount()

这是为什么以及如何在 componentDidMount() 内返回 props

【问题讨论】:

  • 您说第一个console.log 返回一个空字符串,然后第二个也没有返回任何内容。空字符串不是什么 ;) 尤其是当你这样做 state = { city: "" }

标签: javascript reactjs


【解决方案1】:

在构造函数中你应该引用props,而不是this.props

location: props.city

【讨论】:

  • 谢谢,但在 console.log 上仍然返回 null
  • @logos_164 哪一行返回null?你确定返回的值是null?在 JavaScript 中,nullundefined'' 不是一回事。
  • 当我console.log(this.state.location)componentDidMount()
  • this.props.city 是否在 App.js 中定义?如果不是,它将覆盖您在构造函数中设置的空字符串。
  • 是的,它是从index.js传递过来的
【解决方案2】:
        <Route path="/" exact render = {() => <Projections city={this.state.city} {...this.props} />} />

尝试在路线中传递其余的道具

这是因为您在 constructor 中分配了道具,当时它可能会或可能不会收到实际价值。它在组件生命周期中只被调用一次。 你可以使用componentWillReceiveProps 来获取 props,只要它接收到并相应地更新状态。

内部 Projections.js

UNSAFE_componentWillReceiveProps(nextProps){
   if(nextProps.city){
     this.setState({location:nextProps.city})
   }
}

这里正在工作codesand

【讨论】:

  • 谢谢,但我仍然得到相同的结果 state 它返回一个空字符串。
  • 所以这个确切的解决方案不起作用,但它让我找到了我最终开始工作的解决方案,我会尽快发布
猜你喜欢
  • 2020-12-21
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
  • 2019-08-12
  • 2021-07-04
相关资源
最近更新 更多