props.history.push无法正常工作,并重定向到同一条路线

问题描述

因此,我正在制作一个基本的React App,其中包含3个组件:CreateRoom和SetUsername和Window。最初,我使用简单的<Link to="/createRoom" >create a room</Link>导航到createRoom组件,然后在createRoom组件中,在用户设置了房间名称之后,我通过props.history.push({pathname})导航到SetUsername组件,并通过{传递了Room_name {1}},然后当我进入SetUsername组件时,我等待用户设置用户名,然后通过props.history.push()将该用户名再次传递给窗口对象,并使用通过{{1 }}浏览URL参数。但是,当我在createRoom组件中按Submit时,react渲染了在路由props.history.push()处设置的home组件,但是显示的URL是props.history.location.state.room_name,它是SetUsername Component的URL。所以我要实现的行为是,在通过道具传递room_name之后,我在另一个组件中使用该room_name通过URL参数通过SetUsername通过SetUsername导航到窗口组件,但与此同时,还通过道具将用户名传递给了窗口组件。 / p>

当我在createRoom组件中按Submit时,下面是console.log(props)。

"/"

App.js

"/set-user-name"

createRoom.js

{history: {…},location: {…},match: {…},staticContext: undefined}
history:
action: "PUSH"
block: ƒ block(prompt)
createHref: ƒ createHref(location)
go: ƒ go(n)
goBack: ƒ goBack()
goForward: ƒ goForward()
length: 7
listen: ƒ listen(listener)
location: {pathname: "/set-user-name",state: {…},search: "",hash: "",key: "8gq7s3"}
push: ƒ push(path,state)
replace: ƒ replace(path,state)
__proto__: Object
location:
hash: ""
key: "o7exh2"
pathname: "/create-room"
search: ""
state: undefined
__proto__: Object
match:
isExact: true
params: {}
path: "/create-room"
url: "/create-room"
__proto__: Object
staticContext: undefined
__proto__: Object

SetUsername.js

    const App = () => {
      return (
        <Router>
          <Switch>
            <Route path="/create-room" component={CreateRoom} />
            <Route path="/" component={Nav} />
            <Route path="set-user-name" component={SetUsername} />
 <Route path="/:room" component={Window} />
          </Switch>
        </Router>
      );
    };
    
    ReactDOM.render(<App />,document.getElementById("root"));

解决方法

在组件SetUsername.js中,组件const SetUsername = (props) =>[username,SetUsername] = React.useState({})中的状态函数同名。我建议更改为setUsername

我看到的另一个问题是有关变量var room_name = "DEFAULT_USERNAME";的问题。这不是一个好的模式,它将给您的应用程序带来问题。

我在此沙盒中有一个很好的例子,说明如何使用react-router和Hooks进行处理。 https://codesandbox.io/s/simple-example-using-react-router-2yovb?file=/src/App.js