我是跟随代码示例从学习反应的书。它是关于和路由器,用于单页应用程序。
下面是我的项目的链接,在这里我模仿了上面的示例。您可以克隆它并使用npm install和npm run dev运行。(注意:项目也有后端代码,但它是不相关的。问题只是关于我使用静态数据文件的前端部分。)
我可以在本地成功地运行这个示例,但是当我运行我的项目时,当涉及到加载ui组件时,我会发现我的商店是空的。我没有任何编译或控制台错误,我看到应用程序的其他部分运行良好。我花了很多时间调试存储创建代码,但是我不知道为什么它不能工作。请帮忙找出原因。
以下是我的调查结果:
在我的项目中有两个url:/和/cars。/cars url直接读取数据文件,并正确地输出所有数据。
根url应该通过使用redux存储来执行同样的操作。但是,ui组件使用的数据数组为空。我想创建存储的代码(下面)可能有问题,尽管我精确地模仿了代码示例。实际上,我所做的更改只有一个,那就是carsReducer,我将它与示例中的其他还原器完全一样编码。
我还注意到控制台中没有填充localStorage,但它没有给出多少线索。
src/main/resources/static/js/store/index.js
const storeFactory = (initialState=stateData) =>
applyMiddleware(logger, saver)(createStore)(
combineReducers({carsReducer}),
(localStorage['redux-store']) ?
JSON.parse(localStorage['redux-store']) :
initialState
)发布于 2018-02-18 08:08:02
我可以向你推荐一些解决办法:
js/index.js -主要提供程序文件
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { HashRouter } from 'react-router-dom'
import App from './components/App'
import 'bootstrap/dist/css/bootstrap.min.css'
import store from './store'
window.React = React
window.store = store
render(
<Provider store={store}>
<HashRouter>
<App />
</HashRouter>
</Provider>,
document.getElementById('react-container')
)js/store/index.js -存储文件
import { createStore, combineReducers, applyMiddleware } from 'redux'
import {carsReducer} from './reducers'
import stateData from '../../data/cars.json'
let console = window.console
const logger = store => next => action => {
let result
console.groupCollapsed("dispatching", action.type)
console.log('prev state', store.getState())
console.log('action', action)
result = next(action)
console.log('next state', store.getState())
console.groupEnd()
return result
}
const saver = store => next => action => {
let result = next(action)
localStorage['redux-store'] = JSON.stringify(store.getState())
return result
}
const initialState = localStorage['redux-store'] || stateData
const store = createStore(
combineReducers({...carsReducer}),
stateData,
applyMiddleware(logger, saver)
)
export default storeCarsTable.js -和一些针对汽车列表的修正
import PropTypes from 'prop-types'
import CarRow from './CarRow'
const CarsTable = ({cars = []}) =>
<div>
{(cars.length === 0) ?
<p>Cars list is empty.</p> :
<table className="table">
<thead>
<tr>
<th>Ad name</th>
<th>Price</th>
<th>Location</th>
<th>Odometer</th>
<th>Condition</th>
</tr>
</thead>
<tbody>
{
cars.map((car, i) =>
<CarRow key={i} car={car} />
)
}
</tbody>
</table>
}
</div>
CarsTable.propTypes = {
cars: PropTypes.array
}
export default CarsTable发布于 2018-02-18 07:50:04
尝试使用构造函数并在Store上初始化/car-saver/src/main/resources/static/js/index.js
constructor(props) {
super(props);
this.store = configureStore();
}然后把它传递给你的<Provider store={this.store}>
https://stackoverflow.com/questions/48849298
复制相似问题