将用户发送到另一个URL后,我试图创建一种显示消息的解决方案。
一些使用案例是:
这是我要解决的方法:
// EXAMPLE SignIn.tsx:
// inside a functional component I'll reference a Context like so...
const { messages, setMessages } = useContext(MessageContext)
// This would be in an onSubmit function so after a successful sign in,
// I add a message to the existing array (in case others have been added)
// then use history to redirect them else where, where the messages will be
// consumed by another component.
setMessages(['Sign in successful!', ...messages])
history.push('/profile')
// EXAMPLE Messages.tsx:
// This component will display them to the user (how that happens here is irrelevant)
// and then removes them from the global state.
const { messages, setMessages } = useContext(MessageContext)
const [showMessage, setShowMessage] = useState(true)
useEffect(() => {
setShowMessage(messages.length > 0)
// we are about to show these messages so remove them from the context so
// they don't show up anymore.
setMessages([])
}, [messages, setMessages])
这在大多数情况下效果很好,但是在某些情况下,我在尝试更新一个组件同时渲染另一个组件时遇到一些React错误。也许在没有状态管理的情况下还有更好的方法吗?也许全局状态是答案,但我实施的方法有误?
有什么想法吗?您是否有针对此类问题的有效解决方案?
结果是useHistory
可以在history.push
通话期间返回消息,因此我不需要进行自己的消息传递状态管理。
从React router dom的文档中,您可以传递state
哈希中的任何内容,并在.push
调用后呈现的组件中检索它,如下所示:
history.push({
pathname: '/profile',
state: {
// you can put any key/value pairs in here...
message: 'Sign in successful!'
}
})
然后,当您想要检索此消息时,您可以这样操作:
const location = useLocation()
const state = (location?.state) as any
// you can use this in the rendering to show the message
let show = false
if(state && state.message) {
// I was implementing a way to have multiple messages sent
// you may not need to do something like this:
messages.push(((location?.state) as any).message)
// show the message component because a message was sent.
show = true
}