繁体   English   中英

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

[英]With react-router, redux will not work

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

关于

this.props.children并不总是从其父级继承上下文

无法在上下文或道具中找到“商店”

//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属性。 上下文的参数是一个空对象。

//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);

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

也许我们可以注入动作创建者来连接

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'
        });
    }
}

这个解决方案适合儿童组件中的调度操作。有一些限制,期待更好的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM