React Redux中传入子组件的ownProps始终为空对象求助
解决React Redux子组件mapStateToProps中ownProps为空的问题
我刚看了你的代码,发现两个关键问题,咱们一步步来解决:
首先修复父组件的State初始化问题
你的Home组件里没有初始化state,这会导致首次渲染时this.state是undefined,访问this.state.child_component_triggered会直接报错,更别说后续的条件渲染了。先把这个补上:
class Home extends Component { constructor(props) { super(props); // 初始化state,默认不渲染子组件 this.state = { child_component_triggered: false }; } go_to_child_component(){ this.setState({ child_component_triggered: true }) } render() { return ( <div> {this.state.child_component_triggered ? <ChildComponent filter="some_value" /> : null} <button onClick={this.go_to_child_component.bind(this)}>render ChildComponent</button> </div> ) } }
解决子组件ownProps为空的问题
修复完父组件后,咱们来看子组件的ownProps为空的情况。React Redux的connect在类组件中获取ownProps时,偶尔会因为条件渲染的动态挂载导致捕获不到props,你可以试试下面两种方案:
方案一:使用函数返回函数的mapStateToProps
把mapStateToProps改成嵌套函数的形式,确保每次组件props更新时都能拿到最新的ownProps:
const mapStateToProps = () => (state, ownProps) => { console.log(ownProps); // 现在应该能拿到{ filter: "some_value" }了 let obj = {...state}; obj.ownProps = {...ownProps}; return {...obj}; };
方案二:直接在组件内部访问props
如果你不需要在mapStateToProps里立即使用ownProps,也可以直接在子组件的render或者其他生命周期方法中通过this.props.filter获取传入的值,这种方式更直接,也不会受connect的props捕获逻辑影响:
class ChildComponent extends Component { constructor(props) { super(props); console.log(this.props.filter); // 直接获取传入的props } render() { return ( <div> i am child component, filter value is: {this.props.filter} </div> ) } }
额外提示:检查React Redux版本
如果你使用的是React Redux v7及以上版本,确保你的connect用法是符合官方规范的。如果上面的方案都不生效,可以尝试升级到最新稳定版的React Redux,旧版本可能存在一些条件渲染下的props传递bug。
内容的提问来源于stack exchange,提问作者Muho
相关产品推荐
相关产品推荐

