代码之家  ›  专栏  ›  技术社区  ›  strumpy_strudel

路由处理ReactJS和react路由器dom v4中特定于用户的唯一生成的URL

  •  0
  • strumpy_strudel  · 技术社区  · 7 年前

    http://localhost:8000/auth/security_questions/0e51706361e7a74a550e995b415409fdab4c66f0d201c25cb4fa578959d11ffa
    

    所有这些都很好,但我正试图找出如何使用 React react-router-dom v4 . 我走了这条路。

    <Route exact path='/auth/security_questions/:key' component={SecurityQuestions} />
    

    security_questions/ .

    它应该做的是匹配 :key 在数据库加载组件之前。

    1) 如何解析出 部分,以便我可以将其作为值传递给数据库进行验证。

    2) 虽然我对如何处理验证有一个大致的想法,但我不知道该怎么说 反应

    我认为它通常看起来像:

    // ./containers/security_questions.js
    
    componentWillMount() {
        this.props.verifyKey(:key);
    }
    

    然后行动:

    // ./actions/authentication.index.js
    
    export function verifyKey({ :key }) {
        return function(dispatch) {
            axios
                .post(
                    `${ROOT_URL}/api/auth/security_questions/`, 
                    { :key }
                )
                .then(response => {
    
                    dispatch('Finish loading the rest of the component')
                })
                .catch(error => {
                    dispatch(authError(error.response.data.non_field_errors[0]));
                });
        }
    }
    

    3 回复  |  直到 7 年前
        1
  •  2
  •   JustinTRoss    7 年前
    1. 你可以像这样从路径中抓取参数( https://reacttraining.com/react-router/web/api/Route

      <Route path="/user/:username" component={User}/>
      
      const User = ({ match }) => <h1>Hello {match.params.username}!</h1>
      
    2. 您将希望根据verifyKey设置的某些状态有条件地进行渲染。

      componentWillMount() {
        this.props.verifyKey(this.props.match.params.key);
      }
      
      render() {
        if (this.state.permitRender) {
          return <Component>
        } else {
          return <LoadingComponent />
      }
      
        2
  •  1
  •   palsrealm    7 年前

    您可以使用路由上的渲染方法放入验证逻辑并渲染适当的控件。您需要移动操作来验证呈现路由的组件的密钥,而不是SecurityQuestions组件。

    <Route exact 
        path='/auth/security_questions/:key' 
        render={(props)=>{
             let finalComponent= <ComponentToRenderWhenKeyDoesNotMatch/>;
             if(this.props.verifyKey(props.match.params.key)){
                  resultantComponent=<SecurityQuestions/>
             }
             return finalComponent;
         }}
    />
    
        3
  •  0
  •   Austin Greco    7 年前

    路由参数将位于 match.params 道具:

    componentWillMount() {
      this.props.verifyKey(this.props.match.params.key);
    }
    

    https://reacttraining.com/react-router/web/example/url-params

    --

    然后,在你的安全问题成功后,我会在你的reducer中设置一些状态,并在此基础上进行渲染。