当使用react-router 时,redux 的 store 怎么在路由组件间传递?
发布于 8 年前 作者 tangdaohai 9111 次浏览 来自 问答

使用 react-router-redux 讲 react-redux 与 react-router 连接起来。 问题是在于, Route 组件之间的 state 无法关联在一起……

App.js

//路由框架
class App extends React.Component{

    render() {
        return <div className="absolute-center shadow">
           { this.props.children }
       </div>
    }
}
//将 reducer, react-router 与 redux 绑定
const reducer = combineReducers({
    ...reducers,
    routing: routerReducer
});

const store = createStore(reducer, compose(
    applyMiddleware( thunk ),
    window.devToolsExtension ? window.devToolsExtension() : f => f
));
//路由生成规则, 与 redux 结合.
const history = syncHistoryWithStore(browserHistory, store);

ReactDom.render(<Provider store = { store }>
    <Router history = {history}>
        <Route path="/" component={App}>
            <IndexRedirect to="sign-in" />
            <Route path="sign-in" component={ Components.SignIn } />
            <Route path="index" component={ Components.Index } />
        </Route>
    </Router>
</Provider>, document.querySelector("#main"));

SiginIn.js

import { connect } from "react-redux";
import { bindActionCreators } from "redux";
// 在 SignIn 组件上绑定了 user 与相关的 action
@connect( (state) => ({ user : state.user }) , (dispatch) => ({ ...bindActionCreators( UserAction, dispatch ) }));
export default class Singin extends React.Component{
      //...
     render(){
          return ...
     }
}

问题 : 我在 SignIn 里面进行了填写信息登录操作后, 对 store 中的 user 进行了赋值。然后 使用 browserHistory 跳转到了index 组件里面, 那么在 index 组件里面怎么获取 在 signIn 组件中改变的 user ? SignIn 与 Index 组件之间怎么传递 state……

3 回复

通过 redux 框架提供的 connect 高阶函数, 直接从 store 选取需要的数据和申明需要使用的方法传入组件中.

@kylezhang 确实可以……

@connect( state => ( { user : state.user } ) )

昨天我倒腾半天,原来是reducers 里面导出的变量写的不一致…… 所以拿不到

回到顶部