反应错误:“在...的上下文中找不到'商店'”

时间:2019-03-30 04:34:39

标签: javascript reactjs ecmascript-6 redux react-redux

运行我的应用程序时,我收到以下错误消息:

  

在“ Connect(Booklist)”的上下文中找不到“ store”。要么   将根组件包装在中,或传递自定义React   上下文提供者和相应的React上下文   消费者在连接选项中连接到(书本列表)。

我正在使用Create React App并尝试创建列出一些细节的应用。

请参见下面的代码:

app.js

import React, { Component } from 'react';
import './App.css';
import Booklist from './container/book-list';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Booklist />
      </div>
    );
  }
}

export default App;

book-list.js

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 this.props.books.map((book) =>{
            return(
                <ul>{this.renderList()}</ul>
            );
        }
        );
    }
}
function mapStateToProps(state){
    return {
        books: state.books
    }
}
export default connect (mapStateToProps)(Booklist);

books_reducer.js

export default function(){
    return[
        {title: booke1},
        {title: booke2},
        {title: booke3},
        {title: booke3}
    ]
}

Reducer中的index.js

import {combineReducers} from redux;
import booksReducer from './books_reducer'
const rootReducer = combineReducers({
    books: booksReducer
}); 

export default booksReducer;

2 个答案:

答案 0 :(得分:1)

您是否将应用包装在商店中?

import { Provider } from 'react-redux';
const store = createStore(
    combineReducers({
        books: booksReducer
    });
)
<Provider store={store}>
            <App />
        </Provider>

答案 1 :(得分:0)

当我们使用Redux时,我们必须创建store来存储应用程序的所有reducer。我们将所有Reducer合并到单个组件中。

import {combineReducers} from 'redux';
import BooksReducer from './Books';
import ActiveBookReducer from './activeReducer';
const RootReducer = combineReducers({   
 books : BooksReducer,
 activeBookreducer : ActiveBookReducer 
})
 export default RootReducer;

在上面的示例中,我创建了两个Reducer BookReducer和ActiveBookReducer,并使用CombineReducer将它们都存储在一个称为RootReducer的Reducer中。

  1. 您的index.js文件中的第一个导入提供程序和createStore库。
  2. 将RootReducer导入index.js文件中。
  3. 然后使用createStore库获取一个名为store和stored RootReducer的变量。const store = createStore(RootReducer);
  4. 然后在index.js中添加提供程序:<Provider store = {store}> <App /> </Provider>,
  5. 您的代码应如下所示:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import {Provider} from 'react-redux';
    import { createStore } from 'redux';
    import App from './Components/App';
    import RootReducer from './Reducers';
    const store = createStore(RootReducer);
    ReactDOM.render(
     <Provider store = {store}>
      <App />
     </Provider>,
    document.getElementById('root')
    );