如何将状态传递到我的反应路由器路径?

时间:2021-02-09 20:52:30

标签: javascript reactjs react-redux react-router

如何将 appState 添加到我的 React 路由器路径?

我有 react-redux 但我不太确定将 props 传递到我的 react-router 路径的最有效方法。我尝试使用 withRouter,但一直遇到问题。

我想要的只是将道具从一页传递到另一页。

我得到的当前错误是 appState 未定义。

//index.js

<Route path="/dash/:slug" buckets={appState.buckets} render={props => <Bucket {...props} />} />

状态来自于此:

//GetUserBuckets.js

export default function GetUserBuckets()
{
    const classes = useStyles();
    const ListLoading = LoadingComponent(UserBuckets);
    const [appState, setAppState] = useState({
        loading: true,
        posts: null,
    });


    useEffect(() =>
    {
        axiosInstance.get('all/buckets/').then((res) =>
        {
            const allBuckets = res.data;
            setAppState({ loading: false, buckets: allBuckets });
            console.log(res.data);
        });
    }, [setAppState]);

    return (
        <div className={classes.text}>
            <h1>Buckets</h1>
            <ListLoading isLoading={appState.loading} buckets={appState.buckets} />
            <Container className={classes.createBucket}>
                    <CreateDialog />    
            </Container>
        </div>
    );
};

2 个答案:

答案 0 :(得分:0)

您将使用路由器状态传递状态下面显示了 react router dom 文档中的一个示例 https://reactrouter.com/web/api/location

// usually all you need
<Link to="/somewhere"/>

// but you can use a location instead
const location = {
  pathname: '/somewhere',
  state: { fromDashboard: true }
}

<Link to={location}/>
<Redirect to={location}/>
history.push(location)
history.replace(location)

答案 1 :(得分:0)

如果你想通过 Route prop 传递它 - 你可以使用 location prop (location.state),链接如下

https://reactrouter.com/web/api/location

但一般来说,通过 Route 组件传递数据并不是最好的主意,因为如果用户通过链接关注这个特定组件 - 状态将不会附加到 location 属性。

在你的情况下,Route 应该在 GetUserBuckets 组件的渲染(返回)方法中