使用react路由器,redux将无法工作

With react-router, redux will not work

本文关键字:工作 redux react 路由器 使用      更新时间:2023-09-26

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

关于

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

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