简体   繁体   English

每次在 React Native 中渲染组件之前获取数据和 setState

[英]Fetch data and setState every time just before component renders in React Native

There is the case, i have a modal which shows some data from its state ( an array ), and it's state is getting set in componentDidMount() function like docs suggests.在这种情况下,我有一个模态,它显示了来自其 state (一个数组)的一些数据,它的 state 正在像 docsC14A 建议的那样在 componentDidMount() ZC1C425268E68385D1AB5074C17 中设置。 I need to show updated data every time when modal opened up.So i was able to do that with componentWillReceiveProps(nextProps) function, like i showed below.每次打开模式时我都需要显示更新的数据。所以我可以使用 componentWillReceiveProps(nextProps) function 来做到这一点,如下所示。
But what if i want to migrate to getDerivedStateFromProps function?但是如果我想迁移到 getDerivedStateFromProps function 怎么办? How am i going to achieve same behaviour with it?我将如何实现与它相同的行为?

Here is the component code simplified for sake:下面是简化的组件代码:

export class PastOrdersModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      past: {},
      isLoading: false,
      modalVisible: false
    };
  }

  async componentWillReceiveProps(nextProps) {  
    const response = await this.fetchPast();
    this.setState({ past: response });
  }

  async componentDidMount() {
    const response = await this.fetchPast();
    this.setState({ past: response });
  }
   ...
   ... some callback functions for handling modalvisible value ....
   ...
   render(){
   // here rendering state array with this.state.past.map(......) etc.
  }

The fetchPast function makes a GET request to server of mine, all you need to know that it returns an array to me. fetchPast function 向我的服务器发出 GET 请求,您只需要知道它返回一个数组给我。 This is working perfectly.这是完美的工作。 ComponentWillReceiveProps gets called every time because parent component sends modalVisible props everytime. ComponentWillReceiveProps 每次都会被调用,因为父组件每次都会发送 modalVisible 道具。
But componentWillRecieveProps is deprecating and i could not make the same behavior with getDerivedStateFromProps.How should i implement same thing with it.但是 componentWillRecieveProps 已弃用,我无法使用 getDerivedStateFromProps 做出相同的行为。我应该如何用它实现相同的功能。

Note : ı am not going to use redux,i am not going to use mobx, i know how to use them and it's not what i want.注意:我不会使用 redux,我不会使用 mobx,我知道如何使用它们,这不是我想要的。 The thing is the behavior i want is soo simple i don't want to pass values another component, i don't want to pass values another screen, i just want to update a simple component that is all but either the framework is pushing it's limits to make simplest tasks hardests thing ever or i am missing really huge point.(probably latter one:) )问题是我想要的行为太简单了我不想将值传递给另一个组件,我不想将值传递给另一个屏幕,我只想更新一个简单的组件,除了框架正在推动它限制使最简单的任务变得最困难,或者我错过了非常重要的一点。(可能是后一个:))

Note : I know i am not doing anything with nextProps, that was the only solution i found.注意:我知道我没有对 nextProps 做任何事情,这是我找到的唯一解决方案。

You can write your Component as a function so you can use React Hooks您可以将组件编写为 function 以便您可以使用React Hooks

const PastOrdersModal = (props) => {
  const [past, setPast] = useState({});
  const [isLoading, setLoading] = useState(false);
  const [modalVisible, setModalVisibility] = useState(false);

  useEffect(() => {
    const fetchPast = async () => {
      const response = await fetchPast();
      setPast(response);
    };
    if(modalVisible) fetchPast();
  }, [modalVisible])

  useEffect(() => {
    const fetchPast = async () => {
      const response = await fetchPast();
      setPast(response);
    };
    fetchPast();
  }, [])

   ...
   ... some callback functions for handling modalvisible value ....
   ...
   return <YourComponent />

The variables we created inside [] at the top are the ones we are using for the state.我们在顶部[]中创建的变量是我们用于 state 的变量。 The first one will be the state as itself and the second one is a function responsible for updating that state.第一个将是 state 本身,第二个是负责更新 state 的 function。 The useEffect hook will simulate the life cycle methods for Class Components, it receives a callback that will be executed and a second argument. useEffect挂钩将模拟 Class 组件的生命周期方法,它接收将执行的回调和第二个参数。 The second argument is the one that will indicate when it is going to be triggered.第二个参数将指示何时触发。 For instance, you can see 2 useEffect s, the one with the empty array will tell the hook to execute just once, similar as componentDidMount .例如,您可以看到 2 个useEffect ,带有空数组的那个将告诉钩子只执行一次,类似于componentDidMount The other one will be triggered when modalVisible changes, so everytime you change its value it will be executed, that's why we only validate if the modal is visible (is true ) we do the fetch, otherwise the fetch won't be executed另一个将在modalVisible更改时触发,因此每次更改其值时都会执行,这就是为什么我们仅验证模态是否可见(为true )我们进行获取,否则将不会执行获取

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM