简体   繁体   English

React history.push 正在更新 url 但无法加载所需的组件

[英]React history.push is updating url but is not unable to load the desired component

I have 2 components namely 'Navbar' and ' PostInputDailogueBox ' which present inside the App.js component.我有 2 个组件,即“Navbar”和“ PostInputDailogueBox ”,它们存在于 App.js 组件中。 whenever I click a button in the navbar I need to navigate from the ' Navbar ' component to the ' PostInputDailogueBox ' component.每当我单击导航栏中的按钮时,我都需要从“ Navbar ”组件导航到“ PostInputDailogueBox ”组件。 To do this used history.push() but I am not able to navigate to the desired component.为此使用 history.push() 但我无法导航到所需的组件。

below are specified related component:下面是指定的相关组件:

App.js应用程序.js

import React,{Component} from 'react';
import './App.css';
import Navbar from './Components/Navbar/Navbar';
import Posts from './Components/Posts/Posts';
import PostInputDailogueBox from './Components/PostInputDailogueBox/PostInputDailogueBox';
import {Route} from 'react-router-dom';

class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      user: {
        username:'',
        no_of_posts:0
      },
      postDetails: []
    };
  }

  componentDidMount(){
    fetch('http://localhost:3001')
    .then((res)=>res.json())
    .then((data)=>{
      this.setState({postDetails:data},()=>{
        console.log("initialized postDetails");
      });
    });
    const { username, no_of_post} = this.props.location.data;
    this.setState({user: {
      username:username,
      no_of_posts:no_of_post
    }},()=>{
      console.log(this.state.user);
    })
  }

  loadPost = (post) =>{
    this.setState({ 
      postDetails: [post, ...this.state.postDetails] 
    },()=>{
      console.log("loaded post details",post);
    });
  }

  render(){
    const {postDetails, user} = this.state;
    return (
      <div className="App">
        <Navbar/>
        <Posts postDetails = {postDetails}/>
        <Route exact path="/upload" 
              render={(props) => <PostInputDailogueBox {...props} 
                                  username = {user.username}
                                  loadPost = {this.loadPost} />}/>
      </div>
    );
  }
}

export default App;

Navbar.js导航栏.js

In this file I trying to push the state in history so that the postInputDailogueBox can use it.在此文件中,我尝试推送历史记录中的状态,以便postInputDailogueBox可以使用它。

import React,{useState} from 'react';
import './Navbar.css';
import 'fontawesome-free-5.12.0-web/css/all.min.css';
import { useHistory } from "react-router-dom";

const Navbar = (props) =>{
    const [click,setClick] = useState(false);
    let history = useHistory();

    const handleOnClick = () =>{
        setClick(true);
        history.push({
            pathname:'/upload',
            state : {click: click}
        })
    }
    return(
        <div className = "nav-container">
            <div className='nav-img'>
                <img alt='insta-name' src={require('../images/logo_name.png')}/>
            </div>
            <button className="new_post_btn" onClick = {handleOnClick}><i className="fa fa-plus-square font_css" aria-hidden="true"></i></button>
        </div>
    )
}
export default Navbar;

I have tried by writing props.history.push() in place of history.push() but I got an error as我曾尝试用 props.history.push() 代替 history.push() 但我得到了一个错误

TypeError: Cannot read property 'push' of undefined类型错误:无法读取未定义的属性“推送”

PostInputDailogueBox In this file, I am trying to get the state data and loading in the current component state, and whenever it changes I have to manipulate DOM and finally have to send data to App.js using loadUser() PostInputDailogueBox在这个文件中,我试图获取状态数据并在当前组件状态中加载,每当它发生变化时,我必须操作 DOM,最后必须使用 loadUser() 将数据发送到 App.js

import React,{useState,useEffect} from 'react';
import './PostInputDailogueBox.css';

const PostInputDailogueBox = (props) =>{
  const [caption,setCaption] = useState('');
  const [file,setFile] = useState('');
  const {click} = this.props.location.state;
  const [stateClick, setClick] = useState(click);
  const {username, loadPost} = this.props;

  useEffect(()=>{
    const container = document.querySelector('.overlay');
    console.log("click",stateClick);
    console.log("container",container);
    if(stateClick === true)
      container.classList.add('open-overlay');
    else
      container.classList.remove('open-overlay');

  },[stateClick]);

  const onSubmitUpload = (e) =>{
    console.log("on onSubmitUpload");
    e.preventDefault();
    setClick(false);
    fetch('http://localhost:3001/addPost',{
        method:'post',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify({
            username: username,
            caption: caption,
            imageUrl: file
          })
        })
        .then(res => res.json())
        .then(post => {
          if(post){
            console.log("successs");
            loadPost(post);
          }
      })
  }

  return(
    <div className="overlay">
      <div className="overlay-container">
          <form onSubmit = {onSubmitUpload}>
            <input className="inputblk" 
                   type="text" 
                   placeholder="type caption..." 
                   onChange={e => setCaption(e.target.value)}/><br/>
            <input className="inputblk" 
                   type="text" 
                   placeholder="provide File..." 
                   onChange={e => setFile(e.target.value)}/><br/>
            <input className="input-btn" 
                   value = 'Upload'
                   type = "submit"/>
          </form>
      </div>
    </div>
  )
}

export default PostInputDailogueBox;

routes.js :路线.js

import React from 'react';
import App from './App';
import Signin from './Components/Signin/Signin';
import Signup from './Components/Signup/Signup';
import { Route, Switch, Redirect } from 'react-router-dom';

const Routes = () =>{
    return (
        <div>
        <Switch>
            <Route exact path="/signin" component={Signin} />
            <Route exact path="/">
              <Redirect to="/signin" />
            </Route>
            <Route exact path="/signup" component={Signup} />
            <Route exact path="/home" component = {App} />
        </Switch>
        </div>
    )
}

export default Routes;

plz, help in resolving this problem. lz,帮忙解决这个问题。 Thanks in advance.提前致谢。

You need to setup the routes correctly:您需要正确设置路由:

import { BrowserRouter, Switch, Route } from 'react-router-dom'

// ...

<BrowserRouter>
  <Navbar />
  <Posts postDetails={postDetails} />
  <Switch>
    <Route
      exact
      path="/upload"
      render={props => (
        <PostInputDailogueBox
          {...props}
          username={user.username}
          loadPost={this.loadPost}
        />
      )}
    />
  </Switch>
</BrowserRouter>

Also, check https://reactrouter.com/web/example/basic另外,检查https://reactrouter.com/web/example/basic

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 反应路由器使用历史。 History.push 更改 url 但不加载组件 - React Router useHistory. History.push changes url but does not load component React 组件未在 history.push 上重新加载 - React component not reloading on history.push React history.push() 不渲染新组件 - React history.push() not rendering new component 在 React 中,“history.push(&#39;/&#39;)”在某些组件中不起作用 - in React, “history.push('/')” is not working in some component React:通过公共组件中的 history.push 跟踪历史更改 - React: tracking history changes by history.push in common component React history.push重新加载组件。 希望它只加载一次 - React history.push reloads component. Want it to load only once 反应路由器问题:为什么 history.push 更改 url 但不更新组件 - React Router Question: why history.push changes url but doesn't update component React history.push() 更改浏览器 URL,但不重新渲染组件 (BrowserRouter) - React history.push() changing the browser URL, but not re-rendering the component (BrowserRouter) history.push() 重定向 url 但组件不呈现(reactjs 应用程序) - history.push() redirects the url but the component does not render (reactjs application) 在 React 中 history.push() 时无法设置新组件的状态 - Not able to set state of new component when history.push() in React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM