1

我有用 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);

我是反应初学者。请推荐一个好方法

4

1 回答 1

0

为类组件创建的 mapStateToProps。因为你正在使用钩子,你应该使用 useSelector 钩子


   import { useSelector } from 'react-redux';

   function ProjectDetails(props) {
     const [projectValue, setValue] = useState({});
     const proData = useSelector(state => state.projects.project)

     return <div>{JSON.stringify(proData)}</div>;
    }

  const projectDetailsWithHocLoading = withEditHoc(ProjectDetails,actions.apiCall()]);
  export default projectDetailsWithHocLoading;

于 2020-03-06T13:25:08.027 回答