import React from 'react' import { connect } from 'react-redux' import { addTodo } from '../actions' let AddTodo = ({ dispatch }) => { let input return ( <div> <form onSubmit={e => { e.preventDefault() if (!input.value.trim()) { return } dispatch(addTodo(input.value)) input.value = '' }}> <input ref={node => { input = node }} /> <button type="submit"> Add Todo </button> </form> </div> ) } AddTodo = connect()(AddTodo) export default AddTodo
现在,在您的组件中,让AddTodo =({dispatch})=> {您正在将您的道具解构为仅访问调度.
如果您使用mapDispatchToProps,您将使addTodo操作可用作组件的prop,然后像this.props.addTodo一样调用它.所以上面的方法是另一种选择.这取决于你选择你觉得舒服的东西
connect只是通过React上下文传递存储/调度,因此您不必通过许多组件传递存储.您不必使用连接.任何模块/ HOC模式都可以工作,连接恰好是一个方便的东西.
在组件中使用dispatch或使用mapDispatchToProps是同一件事.
但是,使用mapDispatchToProps可以更灵活地构建代码并将所有动作创建者放在一个位置.
根据docs:
[mapDispatchToProps(dispatch,[ownProps]): dispatchProps] (Object or Function):
If an object is passed,each function inside it is assumed to be a Redux action creator. An object with the same function names,but with
every action creator wrapped into a dispatch call so they may be
invoked directly,will be merged into the component’s props.If a function is passed, it will be given dispatch as the first parameter. It’s up to you to return an object that somehow uses
dispatch to bind action creators in your own way. (Tip: you may use
thebindActionCreators()
helper from Redux.)If your
mapDispatchToProps
function is declared as taking two
parameters,it will be called with dispatch as the first parameter and
the props passed to the connected component as the second parameter,
and will be re-invoked whenever the connected component receives new
props. (The second parameter is normally referred to as ownProps by
convention.)If you do not supply your own
mapDispatchToProps
function or object
full of action creators,the defaultmapDispatchToProps
implementation just injects dispatch into your component’s props.