类型'Promise <any>'的参数不能分配给类型'string'的参数

时间:2020-10-23 17:36:11

标签: reactjs typescript asynchronous promise

在初始化React App之前,我先在localStorage中获取用户的信息。然后,由于他的ID,我开始与服务器建立套接字连接。

将用户ID传递给套接字函数时,打字稿声称:

'Promise'类型的参数不能分配给'string'类型的参数

这是我的index.tsx文件:

const user = fetchUser();

if (user) {
  getNotifications(user);
}

ReactDOM.render(
      <App />,
  document.getElementById("root")
);

还有fetchUser()函数:

export async function fetchUser() {
  try {
    if (!localStorage.getItem("MyAppName")) return null;
    const user = await jwt_decode(localStorage.MyAppName);
    updateUser(user);
    return user.id;
  } catch (err) {
    return null;
  }
}

如何解决此问题?如果我删除了async / await,它可以正常工作,但是从性能角度来看,在初始化应用程序之前可以像这样阻塞线程吗?

2 个答案:

答案 0 :(得分:1)

getUser会返回一个用async定义的函数的承诺,您要在解析它之前对其进行操作。因为您在模块全局范围内操作,所以可以执行以下操作,这些操作将以非阻塞方式执行:


    getUser.then(user =>  {
       if(user) {
           getNotifications(user);
       }
    })
    .catch(e => console.log('Error: ', e))

答案 1 :(得分:0)

我假设您的App以某种方式将通知作为道具。我们要异步加载通知,并允许App呈现。提取完成后,App的道具将更改为包括通知。根据您的应用程序的期望,您可以传递一个空的通知数组,也可以添加一些用作标志的道具,例如isLoadingNotifications,这样您就可以知道在应用程序中渲染微调器而不是通知。

所有这些操作都应在一个React组件内完成。可能在树的下方,但是现在让我们将App包裹在OuterApp中。

interface Notification {
  /**... */
}

const OuterApp = () => {

  const [notifications, setNotifications] = useState<Notification[]>([]);

  const loadNotifications = async () => {
    await fetchUser();
    if ( user ) {
      const notes = await getNotifications( user );
      setNotifications( notes );
    }
  }

  useEffect( () => {
     loadNotifications();
    // should probably have a cleanup
  }, [] );

  return (
    <App 
      notifications={notifications}
    />
  )

}

ReactDOM.render(
  <OuterApp />,
  document.getElementById("root")
);