【发布时间】:2018-03-26 04:11:20
【问题描述】:
在获得类似功能之后,我还是 react/redux 的新手
用户.js
class User extends React.Component {
componentWillMount() {
this.props.fetchUser(.....);
}
render() {
return (
<Profile />
)
}
export default connect(null, {fetchUser})(User);
Profile.js
class Profile extends React.Component {
render() {
const { user } = this.props
return (
<h1>{user.profile.name}</h1>
)
}
const mapStateToProps = state => ({
user: state.store.user
});
export default connect(mapStateToProps, {})(Profile)
actions.js
export const fetchUser = (.....) => dispatch => {
fetch()
.....
}
reducers.js
case FETCH_USER:
return {
...state,
user: action.payload.user
};
据我了解,用户组件从 componentWillMount() 上的 connect 调用一个操作 (fetchUser)。该操作调用 api,获取数据,reducer 将其添加到状态内的存储中。 Profile 组件然后可以使用 connect 将来自 fetchUser 的数据映射到 store 中并显示该数据。
看了一些教程,包括https://github.com/reactjs/redux/blob/master/docs/basics/UsageWithReact.md
看起来事情可以在不使用类的情况下稍微简化。
如果我要将 User 和 Profile 组件更改为更实用的方式,我会怎么做?
例如。
const User = () => {
return (
<Profile />
)
}
如何调度 fetchUser 操作以及如何模拟它以使用 componentWillMount() 的流程调用?
还是我把事情复杂化了?
【问题讨论】:
标签: reactjs react-redux