当使用react-redux时,redux 的 store 怎么在路由组件间传递?

#1
const store = configureStore() ;
ReactDOM.render(
        <AppContainer>
            <Provider store={ store }>
                <FakeComponent />
            </Provider>
        </AppContainer>
    , document.getElementById( rootEle ) ) ;

我想在FakeComponent组件中拿到store,我在FakeComponent中试了下this.props.storethis.context.store都是undefined,那redux是如何拿到store的?我的需求是在子组件中拿到store,放全局变量可以,不过不是最佳实践嘛。connect mapStateToProps这些会用,不过我不是需要数据模型,因为要和jquery、angular的第三方通信,所以必须拿到store。

试了下,我在子组件的this._reactInternalInstance._context.store找到了store,但是不推荐的吧

#2

为什么在子组件里加了:

static contextTypes = {
      store: PropTypes.object.isRequired
   }

就可以用this.context.store就可以拿到了?试了下去掉就是undefined了

Could not find “store” in either the context or props
Can’t get store from context

#3

没遇到你的情况,我的store全部都是props传递的。

你可能没有用 react-router-redux

#5

你的redux用法错了吧,去看一下react-redux connect

#6

redux传数据直接用connect就好啊 比如你有两个容器a b 两个reducers a b 然后最后用combinereducers合并成一个 整体reducers 然后这两个容器都用connect连接 connect(select)(容器名字) 你想要容器a 对应reducers a 那么如下 就行了啊
function select(state){ console.log(state) //这里面包括数据a b return { state:state.a //我们只想让a容器使用a数据 } }

#7

嗯,我没有用react-router-redux。props传挺好的

#8

嗯嗯,谢谢。connect的用法这个我知道了。

不过问题自己看了下官方的api,发现要获取到context,缺少了两步重要的配置。
首先
1、父组件(要传递context的组件)的childContextTypes必须声明
2、同时子组件的contextTypes也必须声明
两者同时满足,子组件拿到的this.context.xxx才不会为undefined 。

var App = React.createClass( {
    childContextTypes: {
       userConfig: PropTypes.object.isRequired    // childContextTypes必须声明  这一句很重要
    } ,
    getChildContext(){
        return {
            userConfig: userConfig
        }
    } ,
    render(){
        return ( <div className="app_main">
                    <Child></Child>
                </div> ) ;
    }
} ) ;
class Child extends Component {
   static contextTypes = {
        userConfig: PropTypes.object.isRequired    // 子组件的  contextTypes 必须声明 这句很重要
   }
   render(){
      console.log( this.context.userConfig )    // 拿到了对象
      return ( <div>child</div> ) ;
   }
}

所以在子组件必须声明了store的contextTypes才能在当前组件中用this.context.store拿到吧。
同时也 谢谢@JinYuSha0 、@hyy1115 的回答!

相关文章:
Context,React中隐藏的秘密!

#9

参考我这里小项目,有详细说明 项目地址

#10

恩 找到解决的办法就好啊