繁体   English   中英

如何使用 useEffect React Native 保存数组

[英]how to save array with useEffect React Native

我想使用 react useEffect 保存数组数据。 按照 class 的示例:

async componentDidMount() {
  const users = await AsyncStorage.getItem('users');

  if (users) {
   this.setState({ users: JSON.parse(users) });
  }
 }

 componentDidUpdate(_, prevState) {
  const { users } = this.state;

  if (prevState.users !== users) {
   AsyncStorage.setItem('users', JSON.stringify(users));
  }
 }

如何使用 React Hooks 实现逻辑?


对于componentDidMount逻辑,您可以使用useEffect挂钩:

useEffect(() => {
  const asyncFetch = async () => {
    const users = await AsyncStorage.getItem("users");
    if (users) {
      // setter from useState
      setUsers(JSON.parse(users));
    }
  };
  asyncFetch();
}, []);

对于componentDidMount使用useEffect与 dep 数组和useRef参考。

const prevUsers = useRef();
useEffect(() => {
  const prevUsers = prevUsers.current;

  // Some equal check function
  if (!areEqual(prevUsers, users)) {
    AsyncStorage.setItem("users", JSON.stringify(users));
  }

  prevUsers.current = users;
}, [users]);

请注意,在您当前的代码中, prevState.users !== users始终是 truley ,您比较两个对象并且在 JS {} !== {}中始终得出true

你可以像下面这样尝试,你可以在基于功能的组件中使用钩子,而不是基于 class 的组件

//state declaration similar to class based component
const [usersdata,setUsers] = useState([]); 

const users = await JSON.parse(AsyncStorage.getItem('users')); 

//whenever the value of users changes useEffect will reset the value of users in state useEffect handle the lifecycle in function based component
useEffect(()=>{
      if(users){
         setUsers(JSON.parse(users));
      }
},[users])

对于钩子,逻辑会略有变化,您必须使用 state 来“钩子”您的效果以更新组件,因此当钩子 state 已更新时,组件将更新( componentDidUpdate ),您显然可以钩子多个状态。

如果您选择不挂钩任何 state,则效果将仅在安装组件时执行,就像 ( componentDidMount() )

我看不到让您决定何时更新用户 state 的逻辑,因为您总是从存储中获取它,所以我假设您有某种触发器可以让您验证用户值是否在贮存。

所以你可以像这样重构你的代码:

const [users, setUsers] = useState([]);
const [userHasChanged, setUserHasChanged] = useState(false);

usEffect(async () => {
  // comparing the old users with the new users is not useful since you always fetch the users from the storage, so the optimal is to always set the new array/ object to users, this way you avoid comparing the two objects which is a bit costly.

 const newUsers = await AsyncStorage.getItem("users");
 setUsers(JSON.parse(newUsers));

 setUserHasChanged(false);
  
}, [userHasChanged])

// some code that triggers userHasChanged, you use setUserHasChaned(true)

暂无
暂无

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

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