【问题标题】:React Router, using router props in router.js反应路由器,在 router.js 中使用路由器道具
【发布时间】:2020-04-24 23:01:12
【问题描述】:

我正在尝试使用 ':group' 将状态传递到以下路由。这可能吗?

Router.js 文件(部分):

   const [ groups, setGroups ] = useState([])

    useEffect( () => {
        const result = () => {
            fetch("http://localhost:5000/groups", {method: "GET"})
                .then(response => response.json())
                .then(data => setGroups(data.groups))
                .catch(err => {
                    console.error(err)
                })
            }
            result()
    }, [])

    return (
       <Route 
           exact 
           path={`/groups/:group`} 
           render={ routeProps => 
              <GroupDetails 
                   routeProps={routeProps} 
          /> } 
       />
    )

GroupDetails 页面:只需放置必要的代码

const GroupDetails = ({routeProps, userId }) => {

    const [ details, setDetails ] = useState(routeProps.location.state)

现在,在我的群组页面中,如果我点击特定群组,它会将我带到该页面。但如果输入“www.website.com/groups/groupname”,它将是未定义的,因为 routeProp.location.state 中没有任何内容。

我正在考虑只在顶部组件设置一个 groupId 状态,并在每次单击组页面时执行 setGroupId,并将其传递给路径名 /groups/${groupId}。我可以看到这个工作,但我想知道我是否可以使用 React Router 来做到这一点。

谢谢

【问题讨论】:

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


    【解决方案1】:

    嗯,你可以使用withRouter 来获取参数:group

    这里是 withRouter 的文档:https://reacttraining.com/react-router/web/api/withRouter

    另外,还有一个问题可能对您有所帮助: React - How to get parameter value from query string

    【讨论】:

    • 我了解如何在下部组件中使用查询字符串中的参数值,但我主要关心的是在上部组件中使用它!我会研究一下路由器,非常感谢!
    • 也许你需要的是一个 HOC。
    【解决方案2】:

    通常 location.state 与 history.push 一起使用。当您使用 渲染组件时,您也可以将子组件发送到内部。

    const [ groups, setGroups ] = useState([])
    
        useEffect( () => {
            const result = () => {
                fetch("http://localhost:5000/groups", {method: "GET"})
                    .then(response => response.json())
                    .then(data => setGroups(data.groups))
                    .catch(err => {
                        console.error(err)
                    })
                }
                result()
        }, [])
    
        return (
           <Route 
               exact 
               path={`/groups/:group`} 
           >
           <GroupDetails 
               // pass whatever prop
              />
          </Route>
        )

    在 GroupDetails 组件中,你可以使用 react-router 提供的钩子。他们可能会得到你想要的。

    const GroupDetails = ({routeProps, userId }) => {
        const history = useHistory()
        const {url, path} = useRouteMatch()
        const location = useLocation()
        const parameters = useParams() // :group will be found here
        const [ details, setDetails ] = useState(routeProps.location.state)

    如果我没有理解你的问题或者这没有解决你的问题,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 2019-01-28
      • 2019-08-15
      • 2020-04-05
      • 2022-10-14
      • 2020-04-15
      • 2020-07-07
      相关资源
      最近更新 更多