React路由器在刷新后呈现组件 [英] React router renders component after a refresh

查看:88
本文介绍了React路由器在刷新后呈现组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is a strange issue, but when I try to do a redirect using a link, nothing happens, just the URL changes. But when I refresh the browser the component gets rendered. What am I doing wrong?

我的 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>
                )
            })
        )
    }
}

我正在尝试做什么。当点击使用 Questions 组件呈现的链接时,我正在尝试获取 Question 组件。根据ID,问题组件会有所不同。

What I'm trying to do. I'm trying to get a Question component rendered, when a link rendered with the Questions component is clicked. Based on the id, the Question component will differ.

这是问题组件示例(这是一个列表):

This is the Questions component example (It's a list):

当我点击图片下的链接时,它会更改网址,如下所示: http:// localhost:3000 / question / -LDvDwsIrf_SCwSinpMa ,但没有别的发生了。我必须手动刷新页面才能获得组件。

When I click the link under an image it changes the url, like this: http://localhost:3000/question/-LDvDwsIrf_SCwSinpMa, but nothing else happens. I have to manually refresh the page to get the component.

这是正在呈现的单个问题组件

This is the single Question component being rendered

我缺少什么?

推荐答案

您定义了多个路由器实例。但是,应该只有一个路由器实例。 路由器通常位于 App / Main <中<顶级 / code> / Root 组件。

You define multiple Router instances. However, there should be exactly one Router instance. The Router is typically placed pretty much "top-level" within your App / Main / Root component.

这篇关于React路由器在刷新后呈现组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆