简体   繁体   中英

why after refresh page state is undefined?

 //routes const AppRoute = () => { return ( <BrowserRouter> <div className="container"> <Switch> <Route path='/' component={BooksList} exact/> <Route path='/create' component={BookCreate}/> <Route path='/books/:id' component={BookShow}/> </Switch> </div> </BrowserRouter> ); }; export default AppRoute; //store const store = createStore(reducers, applyMiddleware(Promise)); ReactDOM.render( <Provider store={store}> <AppRoute/> </Provider>, document.getElementById("root") ); 

I use react and redux. I created a BookShow component to show data of one book. Data loads correctly but when I refresh the page I get this error: Type Error: Cannot read property 'title' of undefined and hole state is undefined.

Why did this happen and how can I prevent it from happening? this is my code

 import React from 'react'; import {connect} from 'react-redux' const BookShow = props => { if(!props){ return <div>loading...</div> } return ( <div> <h2 className="text-center">{props.book.title}</h2> <p className="">{props.book.body}</p> {console.log(props)} </div> ); }; const mapStateToProps = (state, props) => { return { book: state.books.find((book) => { return book.id === props.match.params.id }) } }; export default connect(mapStateToProps)(BookShow); 

BookShow is a stateless component, try to make it a class,

import React, { Component } from 'react';

export default class BookShow extends Component {
  render() {
    return (
      <div>
your code...
      </div>
    );
  }
}
import {withRouter} from 'react-router-dom';

export default withRouter(connect(mapStateToProps)(BookShow));

when you start from homePage and then navigate to some book you can use props.match.params.id but when refreshing page you can't. Try to use withRouter to see if it will fix your problem.

I have not tested it though! Try it and let me know.

import React from 'react';
import {connect} from 'react-redux'

    class BookShow extends React.Component{
        constructor(props, context) {
            super(props, context);
            this.state = {
                book: {}
            }
        }


        componentWillMount(){
            const { match: { params }, books } = this.props;
            this.state.book = books.find((book) => {
                return book.id === params.id
            });
        }

        render(){
            const { book } = this.props;

            if(!props){
                return <div>loading...</div>
            }

            return (
                <div>
                  <h2 className="text-center">{book.title}</h2>
                  <p className="">{book.body}</p>
                </div>
              );
        }

    }

    const mapStateToProps = (state) => {
      return {
        books: state.books
      }
    };
    export default connect(mapStateToProps)(BookShow);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM