【问题标题】:how to pass props to lazy loading components?如何将道具传递给延迟加载组件?
【发布时间】:2019-10-20 14:10:09
【问题描述】:

我正在尝试进行网站身份验证。我试图将道具传递给延迟加载模块 但突然我遇到了错误“Uncaught (in promise) TypeError: w is not a function”

我正在使用 react 与 apollo 客户端,react 路由器 并且 graphql 查询也可以完美地工作并且延迟组件的渲染 但我无法将道具传递给延迟加载组件

// App.js
const SignIn = lazy(() => import('pages/signin'));

function App(props) {
  // state to represent user signed in to the site
  let [auth, setAuth] = useState(false);

  function handleAuth (boolean) {
    setAuth(boolean);
  }

  return (
    <>
      <main>
        <Suspense fallback={<div>Loading...</div>}>
          <Switch>
            <Route exact path="/" component={HomePage} />
            <Route 
              path="/signin"
              auth={auth}
              handleAuth={handleAuth}
              render={props => (<SignIn {...props} /> )}
            />
// signin.js
let auth = props.auth;
let handleAuth = props.handleAuth;

return (
    <ApolloConsumer>
      {client => {
        return (
          <>
            <div className="signin-div">
              <h1>Sign in</h1>

              <form
                onSubmit={async e => {
                  e.preventDefault();
                  const { data } = await client.query({
                    query: SIGNIN_ACCOUNT,
                    variables: { email, password }
                  });
                  if (data.signin) {
                    handleAuth(true);
                  }
                }}
                className="signin-form"
              >

我希望 handleAuth(true) 能够完美工作,但我认为 handleAuth(true) 不是函数。下面是错误信息 “未捕获(承诺中)TypeError:w 不是函数”

我应该如何将 props 传递给延迟加载模块?

【问题讨论】:

  • 解决了。我刚刚阅读了反应路由器参考并参考了所述渲染方法的道具与路由道具(匹配,历史,位置)相同。所以我只是将 auth 和 handleAuth 属性直接传递给 SignIn 组件

标签: javascript reactjs react-router


【解决方案1】:

这里没有火箭科学,只是将它的道具直接传递给登录组件,您单独发送道具的原因是因为这些道具是从当时的路线收到的。

 return (
        <>
          <main>
            <Suspense fallback={<div>Loading...</div>}>
              <Switch>
                <Route exact path="/" component={HomePage} />
                <Route 
                  path="/signin"
                  auth={auth}

                  render={props => (<SignIn handleAuth={handleAuth} {...props} /> )}
                />

【讨论】:

  • 动态组件呢,使用循环分配给component={loopComponent}
  • 动态组件?你的意思是延迟加载?
  • 是的,组件正在使用循环分配给路由器......假设它以前保存在数组中......
  • 那么延迟加载呢?你不是刚删了吗?
猜你喜欢
  • 2011-08-03
  • 1970-01-01
  • 2018-08-01
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
相关资源
最近更新 更多