无法将props传递给子组件中的 componentDidMount (React)

IT技术 javascript reactjs
2021-05-13 08:00:28

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

在我中,App.js我通过Router如下方式传递props

应用程序.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 中,我有以下内容:

投影.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);` 也返回一个空字符串。

但是我需要访问city.prop的值componentDidMount()console.log(this.props.city);render()返回props,但不在componentDidMount()

这是为什么,我如何回报props之内componentDidMount()

2个回答

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

location: props.city
        <Route path="/" exact render = {() => <Projections city={this.state.city} {...this.props} />} />

尝试在路线中传递其余的props

这是因为你在constructor那段时间分配了props,它可能会也可能不会获得实际value。它在一个组件生命周期中只被调用一次。您可以componentWillReceiveProps在收到props时使用它来获取props并相应地更新状态。

内部 Projections.js

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

这是工作代码和