console inside MyComponent print value for the first time but value dose not show on view.
import React, { useEffect, useState } from "react";
const withLoading = (WrappedComponent) => {
class WithLoading extends React.Component {
constructor(props) {
super(props)
this.state = { loading: true };
}
componentDidMount() {
setTimeout(() => {
console.log("setTimeout")
this.state = { loading: false };
}, 5000)
}
render() {
console.log("render", this.state.loading)
return <WrappedComponent {...this.props} loading={this.state.loading} />;
}
}
WithLoading.displayName = `withLoading(${WrappedComponent.displayName || WrappedComponent.name})`;
return WithLoading;
}
function MyComponent({ loading }) {
console.log("MyComponent loading", loading)
return (<p>is loading:{loading}</p>)
}
const hoc = withLoading(MyComponent);
export default hoc
2
Answers
Found the problem:
Problem 1: state not changed correctly
Problem 2: Inside My component loading prop must use in correct way.
Change
this.state = { loading: false }
tothis.setState({ loading: false })
: