Код работал нормально в response-redux v5, но при обновлении до v7 я получил следующую ошибку времени выполнения при переходе на страницу с CartContainer:
react-dom.development.js:11102 Uncaught Error: Could not find "store" in the context of
"Connect(CartContainer)". Either wrap the root component in a <Provider>, or pass a custom
React context provider to <Provider> and the corresponding React context consumer
to Connect(CartContainer) in connect options.
Теперь я обертываю * 1015 Компонент * -level в Provider, типичным способом gatsby, вот ReduxWrapper. js file:
import React from 'react';
import { Provider } from 'react-redux';
import { getAllProducts } from './src/actions'
import { createStore, applyMiddleware } from 'redux'
import { createLogger } from 'redux-logger'
import thunk from 'redux-thunk'
import rootReducer from './src/reducers';
const middleware = [ thunk ];
if (process.env.NODE_ENV !== 'production') {
middleware.push(createLogger());
}
const store = createStore(rootReducer,applyMiddleware(...middleware))
store.dispatch(getAllProducts())
export default ({ element }) => (
<Provider store={store}>{element}</Provider>
);
Экземпляр хранилища должен запускаться вниз по потоку в любой контейнер, для которого вызывается метод connect () , кроме того, оба gatsby-Browser. js и gatsby-ssr. js имеют следующее:
export { default as wrapRootElement } from './ReduxWrapper';
соответствующий компонент подключения, CartContainer. js указан ниже:
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { checkout } from '../actions'
import { getTotal, getCartProducts } from '../reducers'
import Cart from '../components/checkout/Cart'
const CartContainer = ({ products, total, checkout }) => (
<Cart
products={products}
total={total}
onCheckoutClicked={() => checkout(products)} />
)
CartContainer.propTypes = {
products: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
quantity: PropTypes.number.isRequired
})).isRequired,
total: PropTypes.string,
checkout: PropTypes.func.isRequired
}
const mapStateToProps = (state) => ({
products: getCartProducts(state),
total: getTotal(state)
})
export default connect(
mapStateToProps,
{ checkout }
)(CartContainer)
Я ожидаю, что у CartContainer будет доступ к магазину, и я подозреваю, что проблема связана с тем фактом, что я обновил response-redux с v5 до v7, поскольку до этого момента все работало нормально. Мои зависимости:
{
"name": "gatsby-starter-default",
"private": true,
"description": "A simple starter to get up and developing quickly with Gatsby",
"version": "1.0.0",
"author": "David W",
"dependencies": {
"@fortawesome/fontawesome": "^1.1.8",
"@fortawesome/fontawesome-free": "^5.12.1",
"@fortawesome/fontawesome-svg-core": "^1.2.27",
"@fortawesome/free-brands-svg-icons": "^5.12.1",
"@fortawesome/free-solid-svg-icons": "^5.12.1",
"@fortawesome/react-fontawesome": "^0.1.9",
"@reach/router": "^1.3.3",
"bootstrap": "^4.4.1",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"gatsby": "^2.19.45",
"gatsby-background-image": "^0.10.2",
"gatsby-image": "^2.2.43",
"gatsby-plugin-env-variables": "^1.0.1",
"gatsby-plugin-manifest": "^2.2.39",
"gatsby-plugin-offline": "^3.0.32",
"gatsby-plugin-react-helmet": "^3.1.23",
"gatsby-plugin-sass": "^2.1.29",
"gatsby-plugin-sharp": "^2.4.3",
"gatsby-source-filesystem": "^2.1.46",
"gatsby-transformer-sharp": "^2.3.13",
"google-map-react": "^1.1.6",
"jquery": "^3.4.1",
"node-sass": "^4.13.1",
"nodemailer": "^6.4.3",
"prop-types": "^15.7.2",
"react": "^16.13.1",
"react-bootstrap": "^1.0.0-beta.17",
"react-dom": "^16.13.1",
"react-fontawesome": "^1.7.1",
"react-helmet": "^5.2.1",
"react-map-gl": "^5.2.3",
"react-redux": "^7.2.0",
"redux": "^4.0.5",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"typescript": "^3.8.3"
},
"devDependencies": {
"prettier": "^1.19.1"
},
"keywords": [
"gatsby"
],
"license": "MIT",
"scripts": {
"build": "gatsby build",
"develop": "gatsby develop",
"format": "prettier --write \"**/*.{js,jsx,json,md}\"",
"heroku-postbuild": "gatsby build",
"start": "gatsby serve",
"serve": "gatsby serve",
"clean": "gatsby clean",
"test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/gatsbyjs/gatsby-starter-default.git"
},
"bugs": {
"url": "https://github.com/gatsbyjs/gatsby/issues"
},
"homepage": "https://github.com/gatsbyjs/gatsby-starter-default#readme",
"main": "gatsby-browser.js"
}