使用react-router,redux将无法正常工作

时间:2015-12-13 07:14:53

标签: javascript reactjs react-router redux redux-thunk

我读过很多类似的问题,没有人适合我。

this.props.children doesn't always inherit the context from its parent

Could not find "store" in either the context or props

//store config
const createHistoryWithBasename = (historyOptions) => {
    return useBasename(createHistory)({
        basename: '/user_home'
    })
}
const finalCreateStore = compose(
    applyMiddleware(thunk, createLogger()),
    reduxReactRouter({
        createHistory: createHistoryWithBasename }),
        devTools()
    )(createStore);

export function configureStore(initialState) {
    const store = finalCreateStore(rootReducer, initialState);
    return store;
}

索引文件,所有路由都嵌套在Provider。

//entry file
let routes = (
    <Route path="/" component={UserHome}></Route>
);

ReactDom.render(
    <Provider store={store} >
        <ReduxRouter>
            {routes}
        </ReduxRouter>
    </Provider>,
    rootElement
);

组件。我记录了 this.props ,没有 dispatch 属性。 context 的参数是一个空对象。

//user_home.js
class UserHome extends React.Component {
    constructor(props, context){
        //context is empty Object
        super(props, context);
    }
    render() {
        //this.props.dispatch is undefined
        return (
            <div className="container">
               test
            </div>
        );
    }

}

function mapStateToProps(state){
    return state;
}
export default connect(mapStateToProps, {
    pushState
})(UserHome);

也许,这是一个简单的问题,但我花了很多时间。希望得到你的帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

也许我们可以将动作创建者注入 connect

import * as ActionCreators from './actions/user_actions';

//we can use the actions in ActionCreators to dispatch the action.

export default connect(mapStateToProps, {
    pushState: pushState,
    ...ActionCreators
})(Component);

行动

//action file
export function xxAction(){
    return dispatch =>{
        dispatch({
            type: 'XX_ACTION'
        });
    }
}

此解决方案适合于子组件中的调度操作。存在一些限制,期待更好的解决方案。