// App.js
render() {
return (
<Switch>
<Route exact path="/" component={A} />
<Route path="/index" component={B} />
</Switch>
)
}
// A.jsx
import Cookies from 'universal-cookie'
handleClick = () => {
const cookies = new Cookies()
cookies.set('a', 'a', { path: '/index' })
this.props.history.push('/index')
}
render() {
return <Component onClick={this.handleClick} />
}
// B.jsx
import Cookies from 'universal-cookie'
componentDidMount() {
const cookies = new Cookies()
console.log(cookies.get('a')) // undefined
}简化后的代码就是这样,路由 / 匹配到页面 A,我在页面 A 触发点击事件之后往 cookie 里塞了一个 a,然后跳转到了路由 /index,但是我没办法在页面 B 的 componentDidMount 中访问到这个 a。在 Chrome 的 devtool 中的确可以看到这个 cookie a 保存成功了,而且如果我在 /index 做一次刷新,那么在 componentDidMount 中就可以访问到这个 a 了。
问题是怎么样才能在不做刷新的前提下直接访问到这个 a 呢?
path 应该以 “/” 结尾,试试