简体   繁体   English

当 2D 数组中的元素在 react native expo 中发生变化时重新渲染页面

[英]Re-rendering the page when an element in the 2D array changes in react native expo

I want to re-run the code below to reload the page whenever the value inside the invitation[1][1] changes, I update these array values using the AsyncStorage in another page, when I tried the following I got the error below.我想重新运行下面的代码以在邀请 [1][1] 中的值发生更改时重新加载页面,我使用另一个页面中的 AsyncStorage 更新这些数组值,当我尝试以下操作时,出现以下错误。 Is there any other way to do so?有没有其他方法可以做到这一点?

const [invitation, setInvitation] = React.useState(Array.from({length: 2},()=> Array.from({length: 2})));

  React.useEffect(()=>
  {
     getUserId();

  },invitation[1][1]);

    async function getUserId() {
      var keys = ["invitationFromURL","Alert"]
      try {
        await AsyncStorage.multiGet(keys , (err, item) => 
        {
          setInvitation(item);
        });
      } catch (error) {
        // Error retrieving data
        console.log(error.message);
      }
    }  


  console.log(invitation);
  console.log(invitation[1][1]);

The error I get Warning: %s received a final argument during this render, but not during the previous render.我收到的错误警告:%s 在此渲染期间收到了最终参数,但在上一次渲染期间未收到。 Even though the final argument is optional, its type cannot change between renders.%s, useEffect即使最后一个参数是可选的,它的类型也不能在渲染之间改变。%s, useEffect

I'm guessing you have something like我猜你有类似的东西

const [invitation, setInvitation] = useState([[], []]);

up at the top of your component.位于组件的顶部。 That means on the first useEffect run invitation[1][1] will be null.这意味着在第一次 useEffect 运行时, invitation[1][1]将为空。 On second run it will have a value.在第二次运行时,它将有一个值。 This is not kosher in React Native.这在 React Native 中不是 kosher 的。 When you call useEffect the final argument must have the same type every time the component renders.当您调用useEffect ,每次组件呈现时,最终参数都必须具有相同的类型

Should be a simple fix -- instead of应该是一个简单的修复——而不是

useEffect(() => {
    getUserId();
  }, invitation[1][1]);

do

useEffect(() => {
    getUserId();
  }, invitation);

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

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