React Redux 生命周期道具
React Redux Lifecycle Props
我正在为我正在构建的 Web 应用程序使用 React 和 Redux。
在大多数情况下,一切都运行良好,但是在从父级传递 props 时我遇到了一个主要问题。
我有一个连接到 redux 并获取我的商店的主要组件。我通过道具就好了:
{ this.props.children && React.cloneElement(
this.props.children,
{
preset: this.state.preset,
children: this.state.babies,
child: this.state.currentChild,
name: this.state.firstName,
}
)}
所以我的特定页面得到了这个道具。然后我将所需的道具传递给子组件,但是我无法访问挂载道具或反应提供的任何其他生命周期方法。它们似乎唯一可用的地方是在 render 方法中,那是在 运行 未定义检查之后:
let child = this.props.child;
if(child.birthdate != undefined) {
// do stuff here
}
看起来我收到了两次 undefined 然后 props 终于进来了,我可以使用它们了。
我的问题是我应该访问哪个生命周期组件来格式化我的数据。我在文档中有 运行 所有可用的方法来尝试 console.log 并查看我所在的位置,但它们都是 return 空的。我真正在渲染中获得道具的唯一地方。
我知道我的解释很差,但我们将不胜感激。
-E
componentWillReceiveProps 生命周期方法应该可以解决问题。您可以获得传入的道具并在那里进行格式化。之后,您可以在组件状态中设置格式化数据,并像这样在渲染方法中使用它。
componentWillReceiveProps(nextProps) {
this.setState({
formattedBirthdate: nextProps.child.birthdate
});
}
第二种选择是在构造函数中执行相同的操作。
之后你可以在渲染中输出格式化的生日,像这样:
this.state.formattedBirthdate && <div>{this.state.formattedBirthdate}</div>
我正在为我正在构建的 Web 应用程序使用 React 和 Redux。
在大多数情况下,一切都运行良好,但是在从父级传递 props 时我遇到了一个主要问题。
我有一个连接到 redux 并获取我的商店的主要组件。我通过道具就好了:
{ this.props.children && React.cloneElement(
this.props.children,
{
preset: this.state.preset,
children: this.state.babies,
child: this.state.currentChild,
name: this.state.firstName,
}
)}
所以我的特定页面得到了这个道具。然后我将所需的道具传递给子组件,但是我无法访问挂载道具或反应提供的任何其他生命周期方法。它们似乎唯一可用的地方是在 render 方法中,那是在 运行 未定义检查之后:
let child = this.props.child;
if(child.birthdate != undefined) {
// do stuff here
}
看起来我收到了两次 undefined 然后 props 终于进来了,我可以使用它们了。
我的问题是我应该访问哪个生命周期组件来格式化我的数据。我在文档中有 运行 所有可用的方法来尝试 console.log 并查看我所在的位置,但它们都是 return 空的。我真正在渲染中获得道具的唯一地方。
我知道我的解释很差,但我们将不胜感激。
-E
componentWillReceiveProps 生命周期方法应该可以解决问题。您可以获得传入的道具并在那里进行格式化。之后,您可以在组件状态中设置格式化数据,并像这样在渲染方法中使用它。
componentWillReceiveProps(nextProps) {
this.setState({
formattedBirthdate: nextProps.child.birthdate
});
}
第二种选择是在构造函数中执行相同的操作。
之后你可以在渲染中输出格式化的生日,像这样:
this.state.formattedBirthdate && <div>{this.state.formattedBirthdate}</div>