【问题标题】:Passing state via this.history.pushState()通过 this.history.pushState() 传递状态
【发布时间】:2016-03-14 03:37:35
【问题描述】:

我正在使用 react-router 1.0 及其历史集成。

import { createHistory, useBasename } from 'history'

const history = useBasename(createHistory)({
    basename: '/base-path'
});

export default (
    <Router history={history}>
        <Route path="/" component={require("Template")}>
            <Route path="sub-page" component={require("SubPage")}/>
        </Route>
    </Router>
);

我正在尝试从我们的 API 和 URL 中删除 ID,并在 JSON 对象中传递 HATEOAS 创建的自我链接。 我想通过 pushState 状态参数传递数据。

onClickEditButton(selfLinkObject) {
    this.history.pushState(selfLinkObject, "/my/url");
}

但是当我尝试获取状态时,它并没有被通过。

import React from "react"
import { History } from "react-router"

export default React.createClass({
    mixins: [History],
    componentDidMount() {
        console.log(this.state);
        console.log(this.history.state);
        console.log(history.state);
    },
    render() {
        <p>Check the console to see if the state is passed from the pushState(state, url, params);</p>
    }
});

这似乎是 pushState 根据Mozilla's pushState documentation 的预期工作方式,因为浏览器将状态对象保存到用户的磁盘,以便在用户重新启动浏览器后可以恢复它们。

有谁知道我如何或是否可以将数据传递给状态,或者是否有更好的方法来做到这一点?

【问题讨论】:

    标签: react-router


    【解决方案1】:

    状态为location,因此,如果它是您的路由组件,您可以通过props 访问它:this.props.location.state 或获取上下文的location 对象。

    查看 v3 文档中的 Pinterest example,这正是您想要的。

    编辑: 这是 React Router v4 中示例的链接: https://reacttraining.com/react-router/web/example/modal-gallery

    【讨论】:

    • 老兄!!!这正是我所需要的......我以为我搜索了文档的每一部分。我真的很感谢你!你是摇滚明星!!
    • 很高兴我能帮上忙。如果在文档中不清楚,请发送 PR 并建议更改。
    • 链接不再存在。
    • 老兄,你是个摇滚!非常感谢。
    • 链接再次存在
    猜你喜欢
    • 2016-05-23
    • 2019-10-10
    • 1970-01-01
    • 2022-01-08
    • 2019-12-14
    • 2017-05-18
    • 1970-01-01
    • 2021-10-14
    • 2017-08-17
    相关资源
    最近更新 更多