我是React的新手。请帮助我。 我正在使用反应路由器(链接,路由,BrowserRouter,交换机)在不同页面之间导航。我在其中一个页面中设置了一个状态,当我导航回到上一页时,该状态会丢失。我应该使用redux来存储状态吗?
答案 0 :(得分:0)
您应该对react-redux进行反应,否则无法获取其他组件的状态,如果您想从其他组件获取状态,则可以将组件A的状态作为道具传递给组件B
例如:
import SpriteKit
import GameplayKit
class PlayerControlComponent: GKComponent, ControlInputDelegate {
var touchControlNode: TouchControlInputNode?
var cNode: CharacterNode?
func setupControls (camera: SKCameraNode, scene: SKScene) {
touchControlNode = TouchControlInputNode(frame: scene.frame)
touchControlNode?.inputDelegate = self
touchControlNode?.position = CGPoint.zero
camera.addChild(touchControlNode!)
if cNode == nil {
if let nodeComponent = self.entity?.component(ofType: GKSKNodeComponent.self) {
cNode = nodeComponent.node as? CharacterNode
}
}
}
func follow(command: String?) {
if cNode != nil {
switch command! {
case "left":
cNode?.left = true
case "cancel left", "stop left":
cNode?.left = false
case "right":
cNode?.right = true
case "cancel right", "stop right":
cNode?.right = false
default:
print(command!)
}
}
}
override func update(deltaTime seconds: TimeInterval) {
super.update(deltaTime: seconds)
cNode?.stateMachine?.update(deltaTime: seconds)
}
}
然后您可以通过类似的道具将状态从组件A传递到组件B
import componentB from "path_to_the_component_b"
答案 1 :(得分:0)
说您有2页。这2页有一些内部状态。 现在,当您从页面A遍历到页面B时。
页面B的状态从constructor
开始(如果您使用的是基于类的组件)直到componentDidMount
被调用。因此,页面B的状态已定义。
现在您正在遍历页面A(通过链接或浏览器),因此页面A收到了新呼叫,它开始调用其内部状态并开始设置整个页面。>
因此您以前的状态现在丢失了。要保留您的状态,您需要使用Redux了解状态管理。
PS:最好从React Hooks开始,然后深入研究Redux以进行状态管理。