React路由器在刷新后呈现组件

时间:2018-06-05 09:22:21

标签: javascript reactjs

这是一个奇怪的问题,但是当我尝试使用链接进行重定向时,没有任何反应,只是URL发生变化。但是当我刷新浏览器时,组件会被渲染。我做错了什么?

我的nav.js

import React from 'react';
import {Navbar, Nav, NavItem, Modal, Button, FormControl} from 'react-bootstrap';
import {BrowserRouter, Link, Route, Switch} from 'react-router-dom';
import {auth} from '../firebase';
import Questions from './questions';
import {About} from './about';
import {Home} from './home';
import {LinkContainer} from 'react-router-bootstrap';
import Question from "./question";

class Navigation extends React.Component {
    constructor(props) {
        super(props);
        this.state = {};
        this.login = this.login.bind(this);
        this.logout = this.logout.bind(this);
        this.openLogin = this.openLogin.bind(this);
        this.handleClose = this.handleClose.bind(this);
    }

    componentDidMount() {
        auth.onAuthStateChanged((user) => {
            if (user) {
                this.setState({
                    user: user
                }, function () {
                    this.props.checkUserState(this.state.user)
                });
            }
        });
    }

    logout() {
        auth.signOut()
            .then(() => {
                this.setState({
                    user: null
                }, function () {
                    this.props.checkUserState(this.state.user)
                });
            });
    }

    login() {
        var email = document.getElementById('email').value;
        var password = document.getElementById('password').value;
        auth.signInWithEmailAndPassword(email, password)
            .then(result => {
                    const user = result.user;
                    this.setState({
                            user: user,
                        },
                        function () {
                            this.props.checkUserState(this.state.user)
                        });
                    document.getElementById('close').click();
                    document.getElementById('questions').click();
                }
            ).catch(e => console.log(e));
    }

    openLogin() {
        this.setState({show: true});
    }

    handleClose() {
        this.setState({show: false});
    }

    render() {
        return (
            <React.Fragment>
                <BrowserRouter>
                    <React.Fragment>
                        <Navbar>
                            <Navbar.Header>
                                <Navbar.Brand>
                                    <Link id='home' to="/">UczIchApp</Link>
                                </Navbar.Brand>
                            </Navbar.Header>
                            <Nav>
                                <LinkContainer id='about' to='/about'>
                                    <NavItem>O nas</NavItem>
                                </LinkContainer>
                                {
                                    this.state.user ?
                                        <React.Fragment>
                                            <LinkContainer id="questions" to='/questions'>
                                                <NavItem>Zadania</NavItem>
                                            </LinkContainer>
                                            <NavItem onClick={this.logout}>Wyloguj się</NavItem>
                                        </React.Fragment>
                                        :
                                        <NavItem onClick={this.openLogin}>Zaloguj się</NavItem>
                                }
                            </Nav>
                        </Navbar>
                        <Switch>
                            <Route exact path="/about" component={About}/>
                            <Route exact path="/questions" component={Questions}/>
                            <Route exact path="/" component={Home}/>
                            <Route path='/question/:id' component={Question}/>
                        </Switch>
                    </React.Fragment>
                </BrowserRouter>
                <Modal
                    show={this.state.show}
                    onHide={this.handleClose}>
                    <Modal.Header
                        closeButton>
                        <Modal.Title> Modal
                            heading </Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <form>
                            <FormControl
                                id="email"
                                type="email"
                                label="Email address"
                                placeholder="Enter email"/>
                            <FormControl id="password" label="Password" type="password"/>
                            <Button onClick={this.login}>Zaloguj</Button>
                        </form>
                    </Modal.Body>
                    <Modal.Footer>
                        <Button id="close" onClick={this.handleClose}>Close</Button>
                    </Modal.Footer>
                </Modal>
            </React.Fragment>
        )
    }
}

export default Navigation;

我的Questions.js

import React from 'react';
import firebase from 'firebase';
// import {Button} from 'react-bootstrap';
import {BrowserRouter as Router, Link, Route} from 'react-router-dom';
import Question from './question';

class Questions extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            currentItem: '',
            username: '',
            questions: []
        };
    }

    componentDidMount() {
        const questionsRef = firebase.database().ref('Works').orderByChild('available').equalTo(true).limitToFirst(10);
        questionsRef.on('value', (snapshot) => {
            let questions = snapshot.val();
            let newState = [];
            for (let question in questions) {
                newState.push({
                    id: question,
                    category: questions[question].category,
                    level: questions[question].level,
                    pointAmount: questions[question].pointAmount,
                    pointBoost: questions[question].pointBoost,
                    photoURL: questions[question].photoURL,
                });
            }
            this.setState({
                questions: newState
            });
        });
    }

    render() {
        return (
            <section id='loopContainer' className='display-question'>
                <div className='wrapper'>
                    <ul style={{listStyleType: 'none'}}>
                        {
                            this.state.questions.map(question => {
                                return (
                                    <li key={question.id}>
                                        <h3>Kategoria: {question.category}</h3>
                                        <p>Poziom: {question.level}</p>
                                        <p>Punkty: {question.pointAmount + question.pointBoost}</p>
                                        <img alt='' style={{width: '20%'}} src={question.photoURL}/>
                                        <Router>
                                            <React.Fragment>
                                                <Link to={`/question/${question.id}`}
                                                      style={{display: 'block', margin: 'auto'}}>Rozwiaz to zadanie
                                                </Link>
                                            </React.Fragment>
                                        </Router>
                                    </li>
                                )
                            })
                        }
                    </ul>
                </div>
            </section>
        )
    }
}

export default Questions;

我的Question.js

import React from 'react';
import firebase from 'firebase';

export default class Question extends React.Component {
    constructor(p) {
        super(p);
        this.state = {
            currentItem: '',
            username: '',
            questions: []
        };
    }

    componentDidMount() {
        const questionsRef = firebase.database().ref('Works').orderByChild('firebaseKey').equalTo(this.props.match.params.id);
        questionsRef.on('value', (snapshot) => {
            let questions = snapshot.val();
            let newState = [];
            for (let question in questions) {
                newState.push({
                    id: question,
                    category: questions[question].category,
                    level: questions[question].level,
                    pointAmount: questions[question].pointAmount,
                    pointBoost: questions[question].pointBoost,
                    photoURL: questions[question].photoURL,
                });
            }
            console.log(newState);
            this.setState({
                questions: newState
            });
        });
    }

    render() {
        return (
            this.state.questions.map(question => {
                return (
                    <section key={question.id} className='display-question'>
                        <div className='wrapper'>
                            <h3>Kategoria: {question.category}</h3>
                            <p>Poziom: {question.level}</p>
                            <p>Punkty: {question.pointAmount + question.pointBoost}</p>
                            <img alt='' style={{width: '80%'}} src={question.photoURL}/>
                        </div>
                    </section>
                )
            })
        )
    }
}

我想做什么。当点击使用Question组件呈现的链接时,我尝试渲染Questions组件。根据ID,Question组件会有所不同。

这是Questions组件示例(它是一个列表):

enter image description here

当我点击图片下方的链接时,它会更改网址,如下所示:http://localhost:3000/question/-LDvDwsIrf_SCwSinpMa,但不会发生任何其他情况。我必须手动刷新页面才能获得组件。

这是正在呈现的单个Question组件

enter image description here

我错过了什么?

1 个答案:

答案 0 :(得分:1)

您定义了多个Router个实例。但是,应该只有一个Router实例。 Router通常位于App / Main / Root组件中的“顶层”。