通过 this.history.pushState() 传递状态 [英] Passing state via this.history.pushState()

查看:27
本文介绍了通过 this.history.pushState() 传递状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using react-router 1.0 and their integration of history.

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,并传递由 HATEOAS 创建的自链接a> 在 JSON 对象中.我想通过 pushState 状态参数传递数据.

I'm attempting to remove IDs from our API and in the URL and pass the self link create by HATEOAS in a JSON object. I would like to pass the data via the pushState state parameter.

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

但是当我尝试获取状态时,它没有被传递.

But when I attempt to get the state it's not being passed.

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 的 pushState 文档 因为浏览器将状态对象保存到用户的磁盘,以便在用户重新启动浏览器后可以恢复它们.

It seems this is the way pushState was intended to work according to Mozilla's pushState documentation because the browser saves state objects to the user's disk so they can be restored after the user restarts the browser.

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

Does any one know how or if I can pass data to the state or if there's a better way to do this?

推荐答案

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

The state is on location so, you can access it via props if it's your route component: this.props.location.state or get the location object of the context.

查看 v3 文档中的 Pinterest 示例,其中正在做你想做的事.

Check out Pinterest example in the v3 docs, which is doing exactly what you want.

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

edit: Here is the link to the example in React Router v4: https://reacttraining.com/react-router/web/example/modal-gallery

这篇关于通过 this.history.pushState() 传递状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆