“Could not find ”store“ in either the context or p

2019-03-06 15:01发布

问题:

This is my booklist container

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


class BookList extends Component{
  renderList(){
    return this.props.books.map((book)=>{
      return(
        <li key={book.title}>{book.title}</li>
      );
    });
  }

  render(){
    return(
      <ul>
       {this.renderList()}
      </ul>
    )
  }
} 

function mapStateToProps(state){
  return{
    books : state.books
  };    
}

export default connect(mapStateToProps)(BookList); 

This is my app.js file

  import React from 'react';
  import { Component } from 'react';
  import BookList from '../containers/book-list';

  export default class App extends Component{
    render(){
      return(
        <div>
        <div>React simple App</div>
        <BookList/>
        </div>
      );
    }
  }

This is my index.js file in Reducers folder

import {combineReducers} from 'redux';
import BooksReducer from './reducer_books';

const rootReducer = combineReducers({
  books:BooksReducer
});

export default rootReducer;

This is my main index.js file which renders app component on

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app';
import './index.css';

ReactDOM.render(
   <App />,
  document.getElementById('root')
);

This is my books reducer

export default function () {
  return [
    {title: 'AAA1'},
    {title: 'BBB2'},
    {title: 'CCC3'},
    {title: 'DDD4'},
  ]
}

Please tell me where I am wrong.

回答1:

Create a store and enclose your components within a Provider like

import {createStore} from 'redux';
import { Provider } from 'react-redux'
import RootReducer form '/path/to/rootreducer';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app';
import './index.css';
const store = createStore(RootReducer);

ReactDOM.render(
   <Provider store={store}>
       <App />
   </Provider>,
  document.getElementById('root')
);