[英]Can't pass state in React router link
我有一個應該鏈接到聊天界面的通知氣泡。
我試圖通過氣泡所在鏈接中的聊天狀態,但沒有運氣。
class NotifBubble extends Component {
componentWillMount() {
this.pathname = "/chat/" + this.props.merchant.id
if (this.props.merchant.id === 0) {
this.pathname = '#';
}
}
render() {
if (typeof this.props.merchant === 'undefined') {
return <div></div>
}
return (
<Link className="notif-bubble-link" to={{
pathname: this.pathname,
state: { merchant: this.props.merchant }
}}><div className="notif-bubble slide-in-right">
{this.props.message}
</div></Link>
);
}
}
export default NotifBubble;
一切正常 - 直到我將狀態 this.props.merchant 傳遞到鏈接中為止。 this.props.merchant 是絕對正確的。
我在這里做錯了什么沒有正確傳遞狀態?
切勿使用this.pathname
來存儲組件狀態。 使用提供的React State API 。
另外,最好在構造函數中初始化狀態(與componentWillMount
相對)
class NotifBubble extends Component {
constructor(props) {
super(props);
const pathname = props.merchant.id === 0 ?
'#' : `/chat/${props.merchant.id}`;
this.state = {
pathname
};
}
render() {
if (typeof this.props.merchant === 'undefined') {
return <div > < /div>
}
return ( <
Link className = "notif-bubble-link"
to = {
{
pathname: this.state.pathname,
state: {
merchant: this.props.merchant
}
}
} > < div className = "notif-bubble slide-in-right" > {
this.props.message
} <
/div></Link >
);
}
}
export default NotifBubble;
要傳遞對象,您需要先對對象進行stringify
處理,
<Link className="notif-bubble-link"
to={{pathname: this.pathname,
state: { merchant: JSON.stringify(this.props.merchant)}
}}>
<div className="notif-bubble slide-in-right">
{this.props.message}
</div>
</Link>
要訪問state
,
const merchant = JSON.parse(this.props.location.state.merchant)
當使用包含這樣的搜索參數或散列參數的路徑名 url 時: /link?id=100
或/link#some-id
那么它不會將狀態對象傳遞到下一個路由,除非您將參數移動到它們自己指定的位置像這樣的屬性:
<Link to={{
pathname: '/link',
search: '?id=100',
hash: '#some-id',
state: {
id: 100,
}
}}>
Click here
</Link>
希望能幫助任何有搜索或哈希參數的 url 的人。 鏈接到 React-Router 文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.