【问题标题】:props.history.push is not working properly and redirecting to same routeprops.history.push 无法正常工作并重定向到同一路线
【发布时间】:2020-12-08 05:42:56
【问题描述】:

所以,我正在制作一个基本的 React 应用程序,包含 3 个组件,CreateRoom 和 SetUsername 和 Window。最初我使用简单的<Link to="/createRoom" >create a room</Link> 导航到 createRoom 组件,然后在 createRoom 组件中,用户设置房间名称后,我通过 props.history.push({pathname}) 导航到 SetUsername 组件并通过 props.history.push() 传递 Room_name,然后一旦我在 SetUsername 组件中,我等待用户设置用户名,然后通过 props.history.push() 再次将该用户名传递给窗口对象,并使用通过 props.history.location.state.room_name 获取的 room_name 来浏览 URL 参数。但是当我在 createRoom 组件中按下提交时,react 会在路由 "/" 处呈现主组件集,但显示的 URL 是 "/set-user-name",这是 SetUsername 组件的 URL。所以我想要实现的行为是,在通过 props 传递 room_name 之后,我在另一个组件中使用该 room_name 通过 URL params 通过 SetUsername 导航到窗口组件,但同时也通过 props 将用户名传递到窗口组件。

下面是我在 createRoom 组件中按下提交时的 console.log(props)。

{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

App.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"));

createRoom.js

import React from "react";
import { withRouter } from "react-router-dom";
const CreateRoom = (props) => {
  console.log(props);
  const [state, setState] = React.useState({});
  return (
    <div className="center-wrapper">
      <input
        className="room-input"
        placeholder="Room Name"
        onChange={(event) => {
          setState({ [event.target.name]: event.target.value });
        }}
        name="room"
      />
      <div
        className="btn"
        onClick={() => {
          props.history.push({
            pathname: `/set-user-name`,
            state: { room_name: state.room },
          });
        }}
      >
        Create Room
      </div>
    </div>
  );
};

export default withRouter(CreateRoom);

SetUsername.js

import React from "react";
import { withRouter } from "react-router-dom";
import InputForm from "./InputForm.js";

var room_name = "DEFAULT_USERNAME";

const SetUsername = (props) => {
  console.log(props);
  React.useEffect(() => {
    room_name = props.history.location.state.room_name;
  }, []);
  const [username, SetUsername] = React.useState({});
  const handleChange = (event) => {
    SetUsername({ [event.target.name]: event.target.value });
  };
  const handleSubmit = () => {
    props.history.push({
      pathname: `/${room_name}`,
      state: { username: username.username },
    });
  };
  return (

    <InputForm
      inp_placeholder={"Enter a display name"}
      pass_placeholder={undefined}
      inp_className={"for-input"}
      pass_className={undefined}
      onChange={handleChange}
      onClick={handleSubmit}
      inputName={"username"}
      passName={undefined}
      inputRequired={true}
      passRequired={false}
      buttonText={"submit"}
    />
  );
};

export default withRouter(SetUsername);

【问题讨论】:

    标签: reactjs react-redux react-router react-router-dom react-props


    【解决方案1】:

    在您的组件SetUsername.js 中,您与组件const SetUsername = (props) =&gt; 具有相同的名称作为[username, SetUsername] = React.useState({}) 中的状态函数。建议改成setUsername

    我可以看到的其他问题是关于变量var room_name = "DEFAULT_USERNAME";。这不是一个好的模式,会给您的应用程序带来问题。

    我有这个沙箱,其中有一个很好的例子,关于使用 Hooks 处理 react-routerhttps://codesandbox.io/s/simple-example-using-react-router-2yovb?file=/src/App.js

    【讨论】:

      猜你喜欢
      • 2014-09-30
      • 2018-02-28
      • 1970-01-01
      • 2017-09-23
      • 2015-08-09
      • 2014-07-01
      • 2015-12-21
      • 2017-03-04
      相关资源
      最近更新 更多