即使组件正在渲染,React Route也不会渲染组件

时间:2019-04-10 11:09:55

标签: javascript reactjs routes react-router

免责声明:我见过Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null,但此问题没有解决方案可以解决我的问题 我正在尝试在App.js这样的React路由中渲染组件

<main style={{marginTop: '1px'}}>
            <div className="App">

                <Switch>
                    <Route exact path ='/' render = {() => <Home toggleFilter={this.state.filterDrawerOpen}/>}/>
                    <Route path='/profile' component ={Profile}/>
                </Switch>


            </div>
        </main>

但是即使我可以在控制台中看到Home组件呈现的控制台日志,也无法呈现Home组件,如这张图片console logs

home组件的长度超过400行,所以我只包含相关代码

import React, { Component } from 'react';
import Auth from '@aws-amplify/auth';
import { API } from 'aws-amplify';
import ProfileRedirect from "./components/ProfileRedirect";
import LoadingAnimation from './components/LoadingAnimation';
import ReadingSpeed from "./components/ReadingSpeed";
import './Tags.css';
import Articles from "./components/Articles";
import { CSSTransitionGroup } from 'react-transition-group'
import FilterArea from './components/FilterArea';
import "react-datepicker/dist/react-datepicker.css";
import FilterDrop from './components/FilterDrop';
import FilterDrawer from './components/FilterDrawer';
import { withRouter } from "react-router";

let apiName = 'userApi';
let path = '/users/';

class Home extends Component {
    constructor(props){
        super(props);
        this.state = {
            isLoading: true,
            firstLogIn: true,
            filterDrawerOpen:false,
            user :{
                phone:"",
                readingSpeed:0,
                email:"",
                username:"",
                articles: [],
                interests: [],
                saved:[],
                filters:{
                    minutes:null,
                    authors:[],
                    sources:[],
                    minDate:{},
                    selectedInterests:[],
                    selectedDate:{}
                }
            }
        }

        this.dateFilter = this.dateFilter.bind(this)



    }

    async componentDidMount(){

        let userEntry;
        let date = new Date();
        date.setMonth(date.getMonth()-1)



        // const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
        const loggedUser = await Auth.currentAuthenticatedUser();

        userEntry = await API.get(apiName,path + loggedUser.username);

        if(userEntry.hasOwnProperty("userName")){
            let uniqueResults;
            let results = await this.callDatabase(userEntry)

            uniqueResults = results.reduce(function (p, c) {
                if (!p.some(function (el) {return (el.title === c.title && el.author === c.author);}))
                    p.push(c);
                return p;
            }, []);

            this.setState({
                isLoading:false,
                firstLogIn:false,
                filterDrawerOpen:false,
                user : {
                    phone:userEntry.userName,
                    readingSpeed:userEntry.readingSpeed,
                    email:userEntry.userEmail,
                    username:userEntry.userName,
                    articles: uniqueResults,
                    interests:userEntry.userInterests,
                    saved: userEntry.savedArticles,
                    filters:{
                        minutes:null,
                        authors:[],
                        sources:[],
                        minDate:date,
                        selectedDate:{},
                        selectedInterests:[]
                    }
                }
            })

        }else {
            this.setState({
                isLoading:false
            })
        }


    }

    async callDatabase (userEntry,sources,freeMode){...}


    authorFilter = selected => {...}

    sourceFilter = selected => {...}

    interestFilter = selected => {...}

    minutesFilter(value) {...}

    componentWillReceiveProps(newProps) {
        if(newProps.toggleFilter !== this.props.toggleFilter){
          this.filterToggleClickHandler();
        }
    }

    filterToggleClickHandler = () => {...}


    filterDropClickHandler = () => {...}

    dateFilter(selected) {...}

    generateOptions = filter => {
        let data;
        if (filter === "author"){
            data  =   this.state.user.articles.reduce(function (p, c) {
                if (!p.some(function (el) { return (el.author === c.author); }))

                    p.push(c);
                return p;
            }, [])
        }else if (filter==="source"){
            let tempData;
            tempData = this.state.user.articles.reduce(function (p, c) {
                if (!p.some(function (el) { return (el.source.name === c.source.name); }))

                    p.push(c);
                return p;
            }, [])
            data = tempData.map(element => element.source)
        }else if (filter==="interest"){
            data  =   this.state.user.articles.reduce(function (p, c) {
                if (!p.some(function (el) { return (el.interest === c.interest); }))

                    p.push(c);
                return p;
            }, [])
        }

        return data
    }

    async updateDataBase(readingSpeed){
        let updates = {
            body:{
                userName:this.state.user.username,
                userEmail:this.state.user.email,
                userPhone:this.state.user.phone,
                userInterests:this.state.user.interests,
                savedArticles:this.state.user.saved,
                readingSpeed:readingSpeed,
            }


        }

        return await API.put(apiName,path,updates);
    }

    filtersArea() {
        let check
        let newDate = this.state.user.filters.selectedDate;
        if(newDate === null){
            check = true
        }else {
            check= Object.entries(newDate).length === 0 && newDate.constructor === Object
        }

        return (
            <div className="container-fluid">
                <div className="col" style={{margin:"0",padding:"6"}}>
                    <FilterArea
                        sourceOptions = {this.generateOptions("source")}
                        interestOptions = {this.generateOptions("interest")}
                        authorOptions = {this.generateOptions("author")}
                        sourceFilter = {this.sourceFilter.bind(this)}
                        interestFilter = {this.interestFilter.bind(this)}
                        authorFilter = {this.authorFilter.bind(this)}
                        selected={!check ? this.state.user.filters.selectedDate:undefined}
                        minDate = {this.state.user.filters.minDate}
                        dateFilter = {this.dateFilter.bind(this)}
                        minutesFilter = {this.minutesFilter.bind(this)}
                    />

                    <FilterDrawer

                        show = {this.state.filterDrawerOpen}
                        sourceOptions = {this.generateOptions("source")}
                        interestOptions = {this.generateOptions("interest")}
                        authorOptions = {this.generateOptions("author")}
                        sourceFilter = {this.sourceFilter.bind(this)}
                        interestFilter = {this.interestFilter.bind(this)}
                        authorFilter = {this.authorFilter.bind(this)}
                        selected={!check ? this.state.user.filters.selectedDate:undefined}
                        minDate = {this.state.user.filters.minDate}
                        dateFilter = {this.dateFilter.bind(this)}
                        minutesFilter = {this.minutesFilter.bind(this)}


                    />
                </div>
            </div>
        );

    }

    checkAuthors(filter,data){
        let result = [];
        let articles = data.map(function(article){
            if(filter.includes(article.author))result.push(article);
        })

        return result
    }

    checkSource(filter,data){
        let result = [];
        let articles = data.map(function(article) {
            if(filter.includes(article.source.name)) result.push(article)
        })

        return result
    }

    checkInterest(filter,data){
        let result = [];
        let articles = data.map(function(article){
            if(filter.includes(article.interest))result.push(article);
        })

        return result
    }

    checkMinutes(filter,filter1,data){
        let result = [];
        let articles = data.map(function (article) {
            if(article.hasOwnProperty("charNumber")){
                if((article.charNumber/filter1)<=filter)result.push(article)
            }

        })
        return result
    }

    checkDate(filter,data){
        let result = [];
        let dA;
        let dB = filter;
        let articles = data.map(function(article){
            dA = new Date(article.publishedAt.substring(0,10))
            if(dB<=dA) result.push(article)


        })
        return result
    }



    render() {
        let filterdrop;
        if(this.state.filterDrawerOpen) {
            filterdrop = <FilterDrop click = {this.filterDropClickHandler}/>
        }
        console.log(this.state)
        const stillLoading = () => {
            return (
                <div className="loading">
                    <LoadingAnimation
                        type = {"spinningBubbles"}
                        color = {"aqua"}
                    />
                </div>);
        }


        const articles =  (filterA, filterS, filterI, filterM) => {

            let articles = this.state.user.articles;
            let newDate = this.state.user.filters.selectedDate;
            let readingTime = this.state.user.readingSpeed;
            let check;
            if(newDate === null){
                check = true
            }else {
                check= Object.entries(newDate).length === 0 && newDate.constructor === Object
            }

            if(!check){
                articles =  this.checkDate(newDate,articles)
            }

            if(filterA.length){
                articles = this.checkAuthors(filterA,articles)
            }

            if(filterS.length){
                articles = this.checkSource(filterS,articles)
            }

            if(filterI.length){
                articles = this.checkInterest(filterI,articles)
            }
            if(!(filterM === null) && filterM!==0){
                articles = this.checkMinutes(filterM,readingTime,articles)
            }

            return(
                <div className="wrapper">
                    {
                        articles.map(function(article) {

                            return (
                                <Articles
                                    article = {article}
                                    key = {article.id}
                                />
                            )

                        })}
                </div> );





        }

        if(this.state.isLoading){
            return (
                stillLoading()
            );


        }else if(!this.state.firstLogIn && this.state.user.articles.length>0 && this.state.user.readingSpeed >0){


            return (
                <CSSTransitionGroup
                    transitionName="example"
                    transitionAppear={true}
                    transitionAppearTimeout={1000}
                    transitionEnter={false}
                    transitionLeave={false}>

                    {this.filtersArea()}
                    {filterdrop}
                    {articles(this.state.user.filters.authors,this.state.user.filters.sources,
                        this.state.user.filters.selectedInterests,this.state.user.filters.minutes)}

                </CSSTransitionGroup>
            );
        }else if(this.state.firstLogIn || this.state.user.readingSpeed === 0){
            return(
                <ReadingSpeed updateDb = {this.updateDataBase.bind(this)}/>
            );
        }
        else if(this.state.user.interests.length === 0){
            return(
                <div>
                    <ProfileRedirect/>
                </div>
            );
        }

    }
}
export default Home;

我尝试过

  const MyHome =(props) => {
      return (
          <Home {...props} toggleFilter = {this.state.filterDrawerOpen}/>
      )
  }   

与其直接在Route中进行渲染,没有任何效果。 这也是index.js的代码

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.css';
import {BrowserRouter as Router, Route} from 'react-router-dom';



ReactDOM.render(
    <Router>
        <Route path='/' render={(props )=> <App {...props}/>}/>
    </Router>,




    document.getElementById('root'));


serviceWorker.unregister();

我想念什么?

0 个答案:

没有答案