0

我有以下代码片段

const [redirectToRoute, setRedirectToRoute] = useState( false );
const { state  }  = useLocation();

 if( redirectToRoute ){
      return <Redirect to={ state?.from }/>
 }

这是使用 React-Router 的应用程序的一部分。我明白这段代码的作用。但是,我对“?”的使用有疑问。句法。什么是 ”?。”。它与“条件属性”或其他东西有关吗?

如果使用console.log(state.from),会报错×TypeError: Cannot read properties of undefined (reading 'from')

但是 console.log( state?.from ) 没有错误

如果有帮助,下面是我在应用程序中使用的受保护路由器的代码。注意,state: { from: location } 部分。这是 <Redirect to={ state?.from }/> 获取其值的地方。

export default function PrivateRoute({ children, ...rest }) {

    return (
      <Route
        {...rest}
        render={({ location }) =>
           fakeAuth.isAuthenticated ? (
            children
          ) : (
            <Redirect
              to={{
                pathname: "/",
                state: { from: location }
              }}
            />
          )
        }
      />
    );
  }

4

0 回答 0