静态值作为钩子输入

Vol*_*byr 5 reactjs react-native react-hooks

我有一个异步获取新数据的获取服务,我想在获取新数据时更新组件。

为了简化事情,假设这是我的设置:

class SomeService {
  static data;

  // can be called by other components (asynchronous)
  static fetchData = async () => {
    data = await someAsynchronousCall() // data gets a new value
  };
}

const HomeScreen = () => {
  useEffect(() => {
    console.log('new data is: ' + SomeService.data);
  }, [SomeService.data]); // I want to trigger this once data changes

  return <View> ... </View>
};
Run Code Online (Sandbox Code Playgroud)

我试过这样的事情,但是当data改变时,useEffect不会被调用。

有没有办法获得所需的行为?

Dav*_*ins 4

useEffect 监听状态更新。SomeService.data 是一个静态变量。您应该使用 Hooks 来实现类似的东西。

const HomeScreen = () => {
  const [data, setData] = useState();
  //Stand for componentDidMount (empty array dependancies)
  useEffect(()=>{
    setData(new SomeService());
  },[])
  useEffect(() => {
    console.log('new data is: ' + data);
  }, [data]); // I want to trigger this once data changes

  return <View> ... </View>
};
Run Code Online (Sandbox Code Playgroud)