【问题标题】:Props not pass in the route though pass it in the render道具虽然在渲染中传递,但不会在路线中传递
【发布时间】:2021-04-30 02:07:34
【问题描述】:

我正在尝试在路由组件中传递道具,我知道我们不能直接传递给它,所以我曾经渲染,但是道具在子组件中仍然未定义。

import React from 'react';
//components
import Register from '../components/register/register';
import Login from "../components/login/login";
import  ForgetPassword from '../components/forget-password/forget-password';
//redux
import {store} from "../redux/store";
import { connect } from 'react-redux';
import actions from "../redux/authentication/actions";
//react-router
import {BrowserRouter,Route,Switch} from "react-router-dom";
//antd
import "antd/dist/antd.css";
//css
import '../global/_global.scss';

function Authentication(props) {
  console.log("PROPS", props)
  return (
    <div className="App">
    <BrowserRouter>
      {/*switch-component will render first that matches the includes path*/}
      <Switch>
        <Route  path='/login' component={Login} />
        <Route  exact  path='/' component={Login}  />
        <Route   path='/register'
          render={(props) => (
              <Register {...props} check={props.registerUser}  />
          )}
                   />
        <Route   path='/forget-password' component={ForgetPassword} />
      </Switch>
    </BrowserRouter>
    </div>
  );
}
function mapStateToProps(state){
  return state.reducers;
}
export default connect(mapStateToProps, actions)(Authentication);

【问题讨论】:

  • 尝试将render={(props) =&gt; (更改为render={() =&gt; (
  • 它工作正常。谢谢,但是如果我这样做了,为什么它不起作用。
  • 因为您尝试传递的道具不是来自render 函数,而是来自您在Authentication 组件中收到的道具。

标签: javascript reactjs react-redux react-router


【解决方案1】:

尝试这样使用

 return (
    <Route
      render={routeProps => (
        
          <Component {...routeProps} />
       
      )}
    />
  );

而不是

return (
        <Route
          render={(routeProps) => (
            
              <Component {...routeProps} />
           
          )}
        />
      );

【讨论】:

  • 请问这有什么不同?据我所知,如果只有一个论点,那么省略括号是完全可以的。我认为问题在于重用已在范围内定义的名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-17
  • 2021-09-08
  • 1970-01-01
  • 1970-01-01
  • 2020-01-21
相关资源
最近更新 更多