正在将操作传递给状态对象,并且操作对象为空

时间:2018-06-14 15:40:29

标签: javascript reactjs redux react-redux

问题说明

使用来自react-redux和params mapStateToProps的map函数,mapDispatchToProps,它们应该设置状态和动作,但是组件成功构建,但是在组件中动作被传递到状态而不是动作。

@query_result_header = 1

以下是从构造函数

调用class Example extends Component{ constructor(state, actions){ super(); console.log(state); // object containing both state and actions console.log(actions); // empty object ... } ... 时打印的内容
console.log(state);

传递状态和操作的代码(同一文件的底部)

{
    state_X:val, 
    state_Y:val, 
    actions:{
        action_X: action_X(),
        ...
    }
}

以下是创建应用程序和加载组件的方式

const mapStateToProps = (state) => {
    return {...state};
};

const mapDispatchToProps = (dispatch) => {
    let bounded = bindActionCreators(Actions, dispatch);
    console.log(bounded); // object with actions {action_X:action_X(), ...}
    return {actions: bounded};
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Example);

const store = createStore( rootReducer, applyMiddleware( thunkMiddleware, // lets us dispatch() functions loggerMiddleware // neat middleware that logs actions ) ); class App extends Component{ render(){ return( <BrowserRouter> <div> <Route path="/example" component={Example}/> </div> </BrowserRouter> ); } } render( <Provider store={store}> <App/> </Provider>, document.getElementById('root'));

的依赖关系
package.json

2 个答案:

答案 0 :(得分:1)

你所看到的实际上是对的。

所有操作和redux状态都在props

在这种情况下,您已将其用作state

作为示例,您可以使用:

this.props.actions.actionX()

叫你actionX()

你可以使用

获得你的stateX
this.props.state_X

这是使用构造函数的文档:https://reactjs.org/docs/react-component.html#constructor

最后

  

你应该在任何其他声明之前调用super(props)。除此以外,   this.props将在构造函数中未定义,这可能导致   虫子

因为我看到你在没有super(props)

的情况下使用它

希望这会对你有所帮助。

答案 1 :(得分:0)

构造函数,作为他的答案中强化的暴食,将所有参数聚合成一个对象,我认为react-redux connect函数将状态和动作加载到两个单独的对象中但是我没有观察到并且做了没看到有使用传播。

所以这个

constructor(state, actions){

应该是

constructor({actions, ...state}){
相关问题