【问题标题】:useState set call not reflecting change immediately prior to first render of appuseState 设置调用未在应用程序首次呈现之前立即反映更改
【发布时间】:2021-09-02 01:40:54
【问题描述】:

React Hooks 新手,不确定如何解决。我在下面的 App.js 文件中有以下 sn-p 代码。

我基本上想要实现的是通过调用getUser() 函数让用户登录,一旦我有了用户ID,然后通过调用函数checkUserAccess() 来检查他们是否是授权用户用于用户ID .

根据validIds 数组中的结果,我检查它是真还是假,并通过setAuthorised() 调用将授权状态设置为真或假。

我的问题是,在我的 App.js 文件中执行我的第一次渲染之前,我需要先处理这个。

目前,它是说我没有被授权,即使我是。

任何人都可以帮忙解决我做错了什么,因为我需要确保在应用程序的第一个组件渲染之前正确设置 authorised useState,即 path="/"

const [theId, setTheId] = useState('');
const [authorised, setAuthorised] = useState(false);


  const checkUserAccess = async (empid) => {
    try {
      const response = await fetch("http://localhost:4200/get-valid-users");
      const allUsers = await response.json();

      const validIds = allUsers.map(({ id }) => id);
      const isAuthorised = validIds.includes(empid);

      if (isAuthorised) {
        setAuthorised(true)
      } else {
        setAuthorised(false)
      }
    } catch (err) {
      console.error(err.message);
    }
  }  
    
    const getUser = async () => {
        try {
          const response = await fetch("http://localhost:4200/get-user");
          const theId= await response.json();
          
          setTheId(theId);
          checkUserAccess(theId);
    
        } catch (err) {
          console.error(err.message);
        }
      }
    
     useEffect(() => {
        getUser();
      }, []);  

【问题讨论】:

  • 我会添加另一个由theId 值触发的useEffect,它应该调用checkUserAccess 函数
  • 我个人会使用 1 个 useSstate 和 1 个 useEffect,.. 否则你会无缘无故地获得多个渲染。
  • @MarioVernari - 您能否使用我的代码 sn-p 提供您的解决方案示例。
  • 如果您查看我发布的示例,我会这样做 -> if (!user) return <div>Loading</div>; 这应该会停止重定向,因为它会等到调用 setUser 后再决定是否重定向。
  • 是的,基本上我和@Keith 做了同样的事情)

标签: javascript reactjs react-hooks


【解决方案1】:

这样它应该可以工作 但请记住,只有当状态中的 theId 存在时,您才必须呈现您的应用,这意味着您的用户已正确获取。

const [state, setState] = useState({ theId: '', isAutorized: false })    
const getUser = async () => {
  try {
    const idResp = await fetch("http://localhost:4200/get-user");
    const theId = await idResp.json();
    const authResp = await fetch("http://localhost:4200/get-valid-users");
    const allUsers = await authResp.response.json();

    const validIds = allUsers.map(({ id }) => id);
    const isAuthorised = validIds.includes(theId);
    setState({ theId, isAuthorised })
  } catch (err) {
    console.error(err.message);
  }
}

useEffect(() => {
   getUser();
}, []);

if (!state.theId) return <div>Loading</div>;

if (state.theId && !isAuthorized) return <AccessNotAllowed />

return <Home />

【讨论】:

    【解决方案2】:

    除非您想在获取用户 ID 时部分呈现,然后获取访问级别。没有理由有多个 useState's / useEffect's。

    只需获取您的用户,然后获取您的访问级别并使用它。

    下面是一个例子。

    const [user, setUser] = useState(null);
    
    const checkUserAccess = async (empid) => {
      const response = await fetch("http://localhost:4200/get-valid-users");
      const allUsers = await response.json();
      const validIds = allUsers.map(({ id }) => id);
      const isAuthorised = validIds.includes(empid);
      return isAuthorised;
    }  
        
    const getUser = async () => {
      try {
        const response = await fetch("http://localhost:4200/get-user");
        const theId= await response.json();
        const access = await checkUserAccess(theId);
        setUser({
          theId,
          access
        });
      } catch (err) {
        console.error(err.message);
      }
    }
        
    useEffect(() => {
      getUser();
    }, []);  
    
    if (!user) return <div>Loading</div>;
    
    return <>{user.theId}</>
    

    【讨论】:

      猜你喜欢
      • 2021-12-12
      相关资源
      最近更新 更多