【发布时间】:2020-03-06 21:25:08
【问题描述】:
我有用 HOC 包装的功能组件。它在 api 调用后返回一些道具。如何在我的子组件中设置状态(功能)。
const withEditHoc = (WrappedComponent, actioneffects) => {
class HOC extends Component {
constructor(props) {
super(props);
this.state = {
loading: true,
};
}
executeAllActions = async (data, id) => {
await Promise.all(data.map(act => this.props.dispatch(act(id)))).then(() =>
this.setState({ loading: false }),
);
};
componentDidMount = () => {
const editpageId = this.props.match.params.id;
this.executeAllActions(actioneffects, editpageId);
};
render() {
console.log(this.state.loading);
return (
<React.Fragment>
<Loading loading={this.state.loading}>
<WrappedComponent {...this.props} />
</Loading>
</React.Fragment>
);
}
}
return HOC;
这是我的 HOC 结构。在 api 调用之后,数据将在 redux 中。 我正在使用 mapToStateProp 为我的功能组件获取道具。(反应版本 16.3) 请对此提出任何建议。
功能组件
function ProjectDetails(props) {
const [projectValue, setValue] = useState({});
const [proData, setProData] = useState({ ...props.project });
useEffect(() => {
setProData({ props.project });//Here I need to set my data, Iam not able to set data here.
}, []);
return <div>{JSON.stringify(props.project)}</div>;
}
function mapStateToProps(state) {
return {
project: state.projects.project,
};
}
const projectDetailsWithHocLoading = withEditHoc(ProjectDetails, [actions.apiCall()]);
export default connect(mapStateToProps, null)(projectDetailsWithHocLoading);
我是反应初学者。请推荐一个好方法
【问题讨论】:
-
您在
actioneffects中得到了什么? -
很可能您需要在 useEffect 的依赖数组(useEffect 的第二个参数)中设置
props.project。类似于:useEffect(()=>{setProData({props.project})},[props.project]) -
嗨@jure 我怀疑在useeffect上传递第二个参数的原因是什么,尝试一个组件会收到道具?