【问题标题】:ReactJS + Router how to access a Redirect's state functional componentsReactJS + Router 如何访问 Redirect 的状态功能组件
【发布时间】:2020-05-23 23:34:15
【问题描述】:

在官方documentation 上,它说要访问传递给重定向到的组件的状态,您可以使用 this.props.location.state

但是我没有使用类组件,因此我没有this.

如何访问重定向组件中传递的状态?

【问题讨论】:

  • 它通过props 向下传递,并且您在函数组件中收到props 作为参数,例如(props) => (<div>{props.location.state}<div>)

标签: reactjs react-router react-router-dom react-router-v4


【解决方案1】:
<Redirect
    to={{
       pathname: "/signin",
       state: { from: props.location, alert: true },
     }}
 />

以下函数标识在重定向状态下是否有警报传递。如果alert:true 显示&lt;div&gt;

let location = useLocation()
function DashboardRedirectAlert() {
    if (location.state?.alert) {
      return <div className="alert alert-warning">Please Signin first</div>;
    } else {
      return <></>;
    }
  }

当您尝试引用上述功能组件时,请确保始终返回某些内容。

【讨论】:

    【解决方案2】:

    功能组件中没有this,所以可以直接通过props任意状态。''attribution''

    【讨论】:

      【解决方案3】:

      您不允许在功能组件中使用this。真正的代码是: Props.location.state.

      实际上this键盘被移除了,因为在类组件中,当我们想要达到功能和属性和状态时使用this,但是你使用功能组件,所以不需要使用这个。

      【讨论】:

        【解决方案4】:

        它在功能组件中运行良好。访问重定向 url 中的值 使用

        {( typeof props.location.state != "undefined" ) && props.location.state }
        

        如果您在没有重定向的情况下访问页面,您还需要添加未定义检查

        【讨论】:

          【解决方案5】:

          在功能组件中,state 属性可用于从 useLocation() 钩子返回的 location 对象。

          此示例使用optional chaining 来测试状态是否存在并包含myVariable

          function LinkToComponent(props) {
            return (
              <Link
                to={{
                  pathname: `/myRoute/${props.id}`,
                  state: { myVariable: true },
                }}
              >
                Click me
              </Link>
            );
          }
          
          function LinkedToComponent(props) {
            const location = useLocation();
            // will render only if `myVariable` was passed as `true` in  Link state
            {
              location.state?.myVariable && <p>my variable is true</p>;
            }
          }
          
          

          【讨论】:

            猜你喜欢
            • 2022-11-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-04-15
            • 2021-07-26
            • 1970-01-01
            • 2021-09-21
            • 2021-01-14
            相关资源
            最近更新 更多