使用mapDispatchToProps和this.props.dispatch()有什么区别

时间:2017-07-26 08:01:34

标签: reactjs redux react-redux redux-thunk

任何人都可以提供 - mapDispatchToPropsthis.props.dispatch()

之间的区别
  • 哪一个用的?
  • 这与 ReduxThunk
  • 有关

我使用this.props.dispatch

代码下方
    /*Action-Navigation*/
/*Navigation Action*/

const init = () => {
    return (dispatch) => {
        dispatch ({
            type : 'NAV_LINKS',
            data : ['Home', 'Summary']    
        })
    }
}

/*Component-Navigation*/
class Navigation extends React.Component {
    constructor(props){
        super(props);
        this.state = {
    };
    }
  componentWillMount() {
    this.props.dispatch(init());   
  }
  componentWillReceiveProps(props){
    console.log(props);
  }
  render() {
    return (
      <div className="navigation-wrap">
        <div className="navigation-header">
          Navigation
        </div>
        {this.props.navigationReducer.navigationLinks.map((links, index) => <div key={index}>{links}</div>)}
      </div>
    )
  }
}

const mapStateToProps = (state={}) => {
    return {
        navigationReducer : state.navigationReducer,
        navigationLinks : state.navigationReducer.navigationLinks
    }
}


let NavigationContainer = ReactRedux.connect(mapStateToProps)(Navigation);


/*Reducer-Navigation*/
/*Navigation Reducer*/

let initialState = {}; 
const navigationReducer = (state=initialState, action) => {
    switch(action.type){
        case 'NAV_LINKS':
            return Object.assign(state, {
                navigationLinks : action.data
            })
        default:
            return state
    }
}

/*Reducer-Index*/
/*combine all reducers*/

const reducers = Redux.combineReducers({
    navigationReducer
});

/*App*/
/*Create a store*/
const store = Redux.createStore(
    reducers,
    Redux.applyMiddleware(ReduxThunk.default)
);

/*Render component to DOM*/
const render = () => {
    ReactDOM.render(
        <ReactRedux.Provider store={store}>
            <NavigationContainer />
        </ReactRedux.Provider>,
        document.getElementById('rootApp')
    );
}

render();

1 个答案:

答案 0 :(得分:3)

使用redux connect时,mapDispatchToProps会使dispatch方法适用于您的道具。这就是您有权在组件中执行this.props.dispatch()的原因。