繁体   English   中英

如何将 state 传递到我的 react-router 路径?

[英]How can I pass a state to my react-router path?

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

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

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

我得到的当前错误是appState

//index.js

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

state 来自此:

//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>
    );
};

您将使用路由器 state 通过 state 以下显示反应路由器 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)

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

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

但通常通过 Route 组件传递数据并不是最好的主意,因为如果用户通过链接访问此特定组件 - state 将不会附加到 location 道具。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM