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

时间:2020-10-03 07:46:10

标签: javascript reactjs react-router react-router-dom

我有2个组件,分别是“ Navbar”和“ PostInputDailogueBox ”,它们存在于App.js组件中。 每当我单击导航栏中的按钮时,都需要从“ 导航栏”组件导航到“ PostInputDailogueBox ”组件。为此,使用了history.push(),但我无法导航到所需的组件。

以下是指定的相关组件:

App.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

在此文件中,我试图将状态添加到历史记录中,以便 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;

我尝试通过编写props.history.push()代替history.push()进行尝试,但是我得到了一个错误

TypeError:无法读取未定义的属性“ push”

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

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,有助于解决此问题。 预先感谢。

1 个答案:

答案 0 :(得分:1)

您需要正确设置路由:

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>

还要检查https://reactrouter.com/web/example/basic