【问题标题】:How to pass data to a page within a <redirect> in React?如何将数据传递到 React 中的 <redirect> 内的页面?
【发布时间】:2018-06-02 04:27:50
【问题描述】:

现在我正在使用重定向到一个新页面,但我不知道如何将数据传递到新页面。这就是我正在做的:-

class ShopsCatOptions extends React.Component{
    constructor(props){
        super(props);
        this.state={            
            shopd: this.props.shop,
            redirect:false

        };        
    }

    render() {
        if (this.state.redirect) {
            return <Redirect push to="./shopdetail" data={this.state.redirect}/>;
        }

        return(
            <div class="expndinnerm" onClick={this.handleOnClick}>
            {
                this.state.shopd        
            }
            </div>
        )
    }

}
export default ShopsCatOptions

正确的做法是什么?

【问题讨论】:

  • 您可以通过共同的祖先传递数据。或者你可以使用 redux。或者您可以尝试新的上下文 api,恕我直言,这不是很直观,但我认为这是一个很好的用例。
  • 有没有像这样的简单实现:-
  • 我能想到的唯一“简单”方法是将参数添加到 URL 并使用 props.match.params.theParamName 获取它们。这仅适用于字符串
  • 如果我希望将 this.state.redirect 值发送到“./shopdetail”,如何在参数中发送它
  • This 是怎么回事。

标签: reactjs react-router


【解决方案1】:

我所做的就是使用历史道具,

this.props.history.push({
             pathname:"/shopdetail",
             state:{
                 key:"value"
              }
            });

在 ShopDetail 组件中,您可以像这样访问对象,

this.props.location.state.key

编辑:要在你的道具中获取历史,你的主要组件应该有,

import { BrowserRouter, Route } from 'react-router-dom';
...
<BrowserRouter>
  <Switch>
    <Route path="/home" component={Home} />
    <Route path="/user" component={User} />
    <Route path="*" component={page404} />
  </Switch>
 </BrowserRouter> 

【讨论】:

  • 请注意,如果有人直接在其浏览器中打开链接,而不是从应用程序内导航,则该组件会有所不同。
  • 组件不会有所不同,但如果直接从浏览器作为应用程序的第一页打开,则道具将不可用
  • 我得到 props.history 未定义如何修复它
  • 要在你的道具中获取历史记录,你必须在你的主 组件中有
猜你喜欢
  • 2018-02-14
  • 1970-01-01
  • 2019-11-17
  • 2018-12-28
  • 2019-02-13
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多