小编典典

如何使用connect w / Redux从this.props获取简单的调度?

reactjs

我有一个连接的简单React组件(映射了一个简单的数组/状态)。为了避免引用商店的上下文,我想要一种直接从道具中获取“发货”的方法。我见过其他人正在使用这种方法,但是由于某些原因无法使用它:)

这是我当前正在使用的每个npm依赖项的版本

"react": "0.14.3",
"react-redux": "^4.0.0",
"react-router": "1.0.1",
"redux": "^3.0.4",
"redux-thunk": "^1.0.2"

这是带有连接方法的组件

class Users extends React.Component {
    render() {
        const { people } = this.props;
        return (
            <div>
                <div>{this.props.children}</div>
                <button onClick={() => { this.props.dispatch({type: ActionTypes.ADD_USER, id: 4}); }}>Add User</button>
            </div>
        );
    }
};

function mapStateToProps(state) {
    return { people: state.people };
}

export default connect(mapStateToProps, {
    fetchUsers
})(Users);

如果您需要查看减速器(没什么令人兴奋的,但是这里)

const initialState = {
    people: []
};

export default function(state=initialState, action) {
    if (action.type === ActionTypes.ADD_USER) {
        let newPeople = state.people.concat([{id: action.id, name: 'wat'}]);
        return {people: newPeople};
    }
    return state;
};

如果您需要查看如何使用Redux配置路由器

const createStoreWithMiddleware = applyMiddleware(
      thunk
)(createStore);

const store = createStoreWithMiddleware(reducers);

var Route = (
  <Provider store={store}>
    <Router history={createBrowserHistory()}>
      {Routes}
    </Router>
  </Provider>
);

更新

看起来如果我在连接中省略了自己的分派(当前上面显示了fetchUsers),我将获得免费分派(只是不确定这是否带有异步操作的设置通常可以正常工作)。人们会混合搭配还是全部还是一无所有?

[mapDispatchToProps]


阅读 319

收藏
2020-07-22

共1个答案

小编典典

默认情况下mapDispatchToPropsdispatch => ({ dispatch })
因此,如果您不指定的第二个参数connect(),则会将其dispatch作为prop注入到组件中。

如果您将自定义函数传递给mapDispatchToProps,则可以使用该函数执行任何操作。
一些例子:

// inject onClick
function mapDispatchToProps(dispatch) {
  return {
    onClick: () => dispatch(increment())
  };
}

// inject onClick *and* dispatch
function mapDispatchToProps(dispatch) {
  return {
    dispatch,
    onClick: () => dispatch(increment())
  };
}

为了节省您的输入,Redux提供bindActionCreators()了以下功能:

// injects onPlusClick, onMinusClick
function mapDispatchToProps(dispatch) {
  return {
    onPlusClick: () => dispatch(increment()),
    onMinusClick: () => dispatch(decrement())
  };
}

到这个:

import { bindActionCreators } from 'redux';

// injects onPlusClick, onMinusClick
function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    onPlusClick: increment,
    onMinusClick: decrement
  }, dispatch);
}

当道具名称与动作创建者名称匹配时,甚至更短:

// injects increment and decrement
function mapDispatchToProps(dispatch) {
  return bindActionCreators({ increment, decrement }, dispatch);
}

如果您愿意,绝对可以dispatch手动添加:

// injects increment, decrement, and dispatch itself
function mapDispatchToProps(dispatch) {
  return {
    ...bindActionCreators({ increment, decrement }), // es7 spread syntax
    dispatch
  };
}

没有官方建议您是否应该这样做。connect()通常用作支持Redux的组件和不支持Redux的组件之间的边界。这就是为什么我们通常觉得它没有意义注入
两个 有时限的行动创造者和dispatch。但是,如果您觉得需要这样做,请随意。

最后,您现在使用的模式是一个快捷方式,它甚至比call更短bindActionCreators。当您要做的只是return时bindActionCreators,您可以忽略呼叫,而不是这样做:

// injects increment and decrement
function mapDispatchToProps(dispatch) {
  return bindActionCreators({ increment, decrement }, dispatch);
}

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

可以这样写

export default connect(
  mapStateToProps,
  { increment, decrement } // injects increment and decrement
)(App);

但是,每当您想要更自定义的内容(例如传递)时,就必须放弃这种简短的语法dispatch

2020-07-22