我正在阅读Redux库的文档,它有这样的例子:
除了读取状态外,容器组件还可以分派动作。以类似的方式,您可以定义一个名为mapDispatchToProps()的函数,该函数接收dispatch()方法并返回您希望注入到表示组件中的回调道具。
这实际上毫无意义。为什么你需要mapDispatchToProps当你已经有mapStateToProps?
它们还提供了以下方便的代码示例:
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
这个函数是什么?为什么它有用?
现在假设有一个redux动作为:
export function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
当你导入它时,
import {addTodo} from './actions';
class Greeting extends React.Component {
handleOnClick = () => {
this.props.onTodoClick(); // This prop acts as key to callback prop for mapDispatchToProps
}
render() {
return <button onClick={this.handleOnClick}>Hello Redux</button>;
}
}
const mapDispatchToProps = dispatch => {
return {
onTodoClick: () => { // handles onTodoClick prop's call here
dispatch(addTodo())
}
}
}
export default connect(
null,
mapDispatchToProps
)(Greeting);
正如函数名所说的mapDispatchToProps(),将调度动作映射到道具(我们组件的道具)
所以prop onTodoClick是mapDispatchToProps函数的一个键,它进一步委托调度addTodo动作。
此外,如果你想精简代码,绕过手动实现,那么你可以这样做,
import {addTodo} from './actions';
class Greeting extends React.Component {
handleOnClick = () => {
this.props.addTodo();
}
render() {
return <button onClick={this.handleOnClick}>Hello Redux</button>;
}
}
export default connect(
null,
{addTodo}
)(Greeting);
这就意味着
const mapDispatchToProps = dispatch => {
return {
addTodo: () => {
dispatch(addTodo())
}
}
}
它基本上是一种速记。所以不用写:
this.props.dispatch(toggleTodo(id));
您将使用mapDispatchToProps,如示例代码所示,然后在其他地方编写:
this.props.onTodoClick(id);
或者在这种情况下,你会把它作为事件处理程序:
<MyComponent onClick={this.props.onTodoClick} />
这里有一段丹·阿布拉莫夫的视频:
Redux:使用connect()生成容器
mapStateToProps, mapDispatchToProps and connect from react-redux library provides a convenient way to access your state and dispatch function of your store. So basically connect is a higher order component, you can also think as a wrapper if this make sense for you. So every time your state is changed mapStateToProps will be called with your new state and subsequently as you props update component will run render function to render your component in browser. mapDispatchToProps also stores key-values on the props of your component, usually they take a form of a function. In such way you can trigger state change from your component onClick, onChange events.
从文档:
const TodoListComponent = ({ todos, onTodoClick }) => (
<ul>
{todos.map(todo =>
<Todo
key={todo.id}
{...todo}
onClick={() => onTodoClick(todo.id)}
/>
)}
</ul>
)
const mapStateToProps = (state) => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter)
}
}
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
function toggleTodo(index) {
return { type: TOGGLE_TODO, index }
}
const TodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
还要确保你熟悉React的无状态函数和高阶组件