React-Router v4,URL更改但组件未呈现

时间:2018-09-23 16:48:25

标签: javascript reactjs react-router

我已经尝试了所有方法,但是在URL更改时无法呈现组件。没有错误消息,没有安装,react-redux已安装但尚未使用,所以这不是问题。当我从Google chrome React开发工具中检查它时,什么都没有发生,没有匹配,历史与其他任何东西都没有。我找不到解决方案,有什么办法可以使它起作用?

https://codesandbox.io/s/vm3x9n4k67

这是我的.gallery { display: flex; flex-wrap: wrap; align-items: center; max-height: 100%; justify-content: space-around; } .gallery a { text-decoration: none; margin: 0; padding: 0; } .gallery img { max-width: 15%; margin: 10px; border: 3px solid #000000; box-shadow: 3px 3px 3px #22211D; } 。我从react-router-dom导入NavBar.js并实现了这些

NavLink

这是我的Layout.js渲染属性:

import React from 'react'
import classes from "./NavBar.css";
import { NavLink } from 'react-router-dom';


const NavBar = (props) => {
    return (
    <div className={classes.NavBar}>
        <h1 className={classes.NavBar_list} >foodbase</h1>
        <ul className={classes.NavBar_list}>

            <NavLink to="/auth"> <li className={classes.NavBar_list_item}>Signin</li></NavLink>
            <NavLink to="/"><li className={classes.NavBar_list_item}>Main Page</li></NavLink>

        </ul>
    </div>
  )
}

export default NavBar

最后是app.js:

 render() {
          let recipes = [];
          if (this.state.recipes.length > 0) {
          recipes = this.state.recipes;
    }

    return (

        <div>
            <NavBar/>
            <SearchBox
                onChangeHandler={this.onChangeHandler}
                value={this.state.inputValue}
                onSearchClick={this.onClickedHandler} />
            <section className={classes.SearchSection}>
                <ul className={classes.SearchResultArea}>
                    <SearchResults
                        Results={recipes}
                    ></SearchResults>
                </ul>
            </section>

        </div>
    )
}

when clicked Signin

Main Page

1 个答案:

答案 0 :(得分:2)

我假设您需要将Route组件直接放入Switch中,并且不要忘记在children中渲染Layout。所以试试这个:

app.js:

class App extends Component {
  render() {

  return (
  <div>
    <BrowserRouter>
      <Layout>
        <Switch>
          <Route path="/auth" component={Auth} />
          <Route path="/" exact component={SearchBox} />
        </Switch>
      </Layout>
    </BrowserRouter>
    </div>
    );
  }
}

Layout.js

render() {
  // ...

  return (
    <div>
      <NavBar />
      { this.props.children } // <-- your route specific components
    </div>
  )
}