【问题标题】:Spread operator with React Typescript使用 React Typescript 的扩展运算符
【发布时间】:2018-10-17 09:45:39
【问题描述】:

我有一个单页应用程序,重定向实现为

const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
    Acc.isLoggedIn === true
        ? <Component {...props} />
        : <Redirect to={{
            pathname: '/login',
            state: { from: props.location }
        }} />
)} />

)

export { PrivateRoute };

我正在尝试更新它以使其能够像这样工作

interface IPrivateRouteProps {
}

interface IPrivateRouteState {
  isAuthenticated?: boolean
}

export class PrivateRoute extends React.Component<IPrivateRouteProps, IPrivateRouteState> {
constructor(props: IPrivateRouteProps) {
    super(props);

    this.state = ({ isAuthenticated: null });
}

componentDidMount() {
    Acc.isAuthenticated()
        .then(isAuthenticated => {
            this.setState({ isAuthenticated: isAuthenticated });
        });
}

render() {
    if (this.state.isAuthenticated == null) {
        return null;
    }
    else if (this.state.isAuthenticated) {
        return <Route {...rest} render={(props) => (<Component {...props} />)}/>
    }
    else {
        return <Route {...rest} render={(props) => (<Redirect to={{ pathname: '/login', state: { from: props.location } }} />)}/>
    }
}
}

如何在 typescript 中使用扩展运算符传递道具?

更新

不用说,我不仅仅依靠客户端代码进行身份验证。

我已经尝试过了,但没有帮助:Spreading react props in tsx in typescript 2.3.1

【问题讨论】:

  • 您遇到的错误是什么?同样isAuthenticated 只能是booleanundefined 根据IPrivateRouteState 不为空。
  • 错误是“找不到名字'rest'。”
  • 另外,rest 没有在 PrivateRoute 中定义,所以从技术上讲,你是在尝试传播 undefined
  • 您只能将spread与对象或数组一起使用
  • Typescript 与它无关。你只是忘了定义rest 变量

标签: reactjs typescript react-tsx


【解决方案1】:

rest 未定义。

你的意思是:

return &lt;Route {...this.props} render={(props) =&gt; (&lt;Component {...props} /&gt;)}/&gt;

【讨论】:

  • 当我尝试时它只是不重定向。
  • 这一行:return &lt;Route {...rest} render={(props) =&gt; (&lt;Redirect to={{ pathname: '/login', state: { from: props.location } }} /&gt;)}/&gt; 应该更像:return &lt;Redirect to={{ pathname: '/login', state: { from: props.location } }} /&gt;
猜你喜欢
  • 2021-01-16
  • 2020-01-26
  • 2018-05-15
  • 2022-09-23
  • 2020-04-06
  • 2019-08-10
  • 2023-03-25
  • 2021-09-02
  • 2023-02-25
相关资源
最近更新 更多