我是 React/Redux 新手,感谢您的帮助。我正在参加有关此主题的 Udemy 类(class)。类(class)讲师创建了一个这样的组件。
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchUser } from '../actions';
class User extends Component {
componentDidMount(){
this.props.fetchUser(this.props.userId);
}
render(){
const { user } = this.props;
if(!user) return null;
return(
<div className="header"> User Info: {user.name}</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
return { user: state.users.find( user => user.id === ownProps.userId)};
};
export default connect(mapStateToProps, { fetchUser })(User)
我的问题:为什么在componentDidMount()
里面他的前缀是fetchUsers()
与 this.props
?
事实并非如此,他正在通过fetchUsers()
作为来自父组件的 Prop 。这就是父级使用此组件的方式 <User userId={post.userId}/>
注意:此代码有效
最佳答案
这是因为这一行:
导出默认连接(mapStateToProps, { fetchUser })(User)
connect
的第二个参数称为 mapDispatchToProps
,它将操作添加到 props
来自docs :
connect can accept an argument called mapDispatchToProps, which lets you create functions that dispatch when called, and pass those functions as props to your component.
const mapDispatchToProps = dispatch => {
return {
// dispatching plain actions
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' }),
reset: () => dispatch({ type: 'RESET' })
}
}
您的代码使用“对象速记”形式。
关于reactjs - React-Redux:在 React 组件中使用操作创建器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54696368/