Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

reactjs - Use Hook to populate state in React

I am trying to use Hook to populate state in below way.

class CreateService extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      serviceToUSe: []
    };
  }


  useEffect(() => {
    if (window.location.hostname == 'myhost') {
        this.setState({ serviceToUSe: require('../public/service/myhost.com.json') })
    } else {
      this.setState({ serviceToUSe: require('../public/service/default.json') })
    }
    });
  
}

I would like to populate serviceToUSe at the time of loading the component. But I am getting error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You cannot use Hooks in a class component. Hooks are to be used only in Functional Component

const CreateService = () => {

  const [serviceToUse, setServiceToUse] = useState([])
   


  useEffect(() => {
    if (window.location.hostname == 'myhost') {
      setServiceToUse([require('../public/service/myhost.com.json'])
    } else {
      setServiceToUse([require('../public/service/default.json')])
    }
  }, []);
  
}

You syntax for hooks aren't correct either. Learn more about Hooks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...