所以我可能会过度思考这个问题,但我似乎无法使我的组件异步工作。
基本上我使用thunk来调度一个动作,该动作将从本地服务器检索JSON,一旦接收到它,将其传递给reducer并更新状态,从而渲染组件。
相反,组件将应用程序的初始状态作为{u'decrypted': True, u'fcnt': 3, u'timestamp': u'2016-11-30T17:50:00.533Z', u'dataFrame': u'AB3hqqqpVVVOAAA=', u'id': 1480528200533L, u'sf_used': 10, u'snr': -8.5, u'rssi': -116, u'port': 5}
{u'decrypted': True, u'fcnt': 5, u'timestamp': u'2016-11-30T17:50:35.613Z', u'dataFrame': u'AB3hqqqpVVVOAAA=', u'id': 1480528235613L, u'sf_used': 10, u'snr': -5.8, u'rssi': -119, u'port': 5}
{u'decrypted': True, u'fcnt': 7, u'timestamp': u'2016-11-30T17:51:50.609Z', u'dataFrame': u'AB7hqqqpVVVOAAA=', u'id': 1480528310609L, u'sf_used': 10, u'snr': -8.8, u'rssi': -120, u'port': 5}
{u'decrypted': True, u'fcnt': 9, u'timestamp': u'2016-11-30T17:53:23.504Z', u'dataFrame': u'AB7hqqqpVVVOAAA=', u'id': 1480528403504L, u'sf_used': 10, u'snr': -9.2, u'rssi': -116, u'port': 5}
{u'decrypted': True, u'fcnt': 13, u'timestamp': u'2016-11-30T17:55:25.060Z', u'dataFrame': u'AB7iqqqpVVVOAAA=', u'id': 1480528525060L, u'sf_used': 10, u'snr': -8.5, u'rssi': -111, u'port': 5}
{u'decrypted': True, u'fcnt': 15, u'timestamp': u'2016-11-30T17:56:48.140Z', u'dataFrame': u'AB7iqqqpVVVOAAA=', u'id': 1480528608140L, u'sf_used': 10, u'snr': -8.2, u'rssi': -110, u'port': 5}
空对象接收,因此在使用{}
呈现组件时会出错。
这就是我所拥有的:
index.js
map
操作/ index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import thunk from 'redux-thunk';
import promise from 'redux-promise';
import App from './components/app';
import VotesContainer from './containers/votes-container';
import NewPoll from './containers/newpoll';
import VoteTemplate from './components/vote-template';
import Login from './components/auth/login';
import Signup from './components/auth/signup';
import reducers from './reducers/';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducers, composeEnhancers(applyMiddleware(thunk)))
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={VoteTemplate} />
<Route path="allposts" component={VotesContainer} />
<Route path="login" component={Login} />
<Route path="signup" component={Signup} />
<Route path="newpoll" component={NewPoll} />
</Route>
</Router>
</Provider>
, document.querySelector('#project'));
容器
import axios from 'axios';
const ROOT_URL = 'http://localhost:1234';
import { browserHistory } from 'react-router';
import { FETCH_VOTES, CAST_VOTE } from './types';
export function fetchVotes(){
return function(dispatch){
axios.get(`${ROOT_URL}/newpost`)
.then(response => {
console.log('Dispatch!!')
dispatch({
type: FETCH_VOTES,
payload: response.data
})
})
}
}
答案 0 :(得分:1)
您应该根据组件中的预期设置商店的初始状态。
如果您不这样做,那么您不应该期望所有数据都在render
。数据仅在获取后才会出现,直到那时您还可以在组件中添加一些安全检查。