【问题标题】:What is difference between using mapDispatchToProps and this.props.dispatch() [duplicate]使用 mapDispatchToProps 和 this.props.dispatch() 有什么区别 [重复]
【发布时间】:2018-01-01 10:00:04
【问题描述】:

谁能提供-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();

【问题讨论】:

标签: reactjs redux react-redux redux-thunk


【解决方案1】:

当使用 redux 连接时,mapDispatchToProps 使 dispatch 方法可用于您的道具。这就是为什么你可以在你的组件中访问this.props.dispatch()

【讨论】:

    猜你喜欢
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 2011-09-27
    • 2013-04-22
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多