我正在做我的第一个react.js应用程序。由于Visual 2017中react & redux模板项目的一些问题,我在Visual 2017中得到了一个Web API,在Visual代码中得到了一个完全不同的react项目(我不知道这是否相关)。我正在尝试使用我的Web,但是我的action.payload.data总是没有定义。另外,我得到了一个跨原点的错误。我不明白我做错了什么。
src/actions/index.js
import axios from 'axios';
export const FETCH_HOME = 'fetch_home';
const R00T_URL = 'http://localhost:52988/api';
export function fetchHome() {
const request = axios.get(`${R00T_URL}/home`, { crossdomain: true });
console.log(`request: ${request}`);
return {
type: FETCH_HOME,
payload: request
};
}
src/reducers/reducer_home.js
import { FETCH_HOME } from '../actions';
export default function(state = {}, action) {
if (typeof action.payload === 'undefined') {
console.log('action undefined');
return state;
}
switch (action.type) {
case FETCH_HOME:
console.log(`action: ${action}`);
return action.payload.data;
default:
return state;
}
}
src/components/home_index.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchHome } from '../actions';
class HomeIndex extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.fetchHome();
}
render() {
console.log(`props: ${this.props}`);
return (
<div>
<h1>Home Index</h1>
</div>
);
}
}
function mapStateToProps(state) {
return { props: state.props };
}
export default connect(mapStateToProps, { fetchHome })(HomeIndex);
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route } from 'react-router-dom';
import reducers from './reducers';
import HomeIndex from './components/home_index';
import promise from 'redux-promise';
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<div>
<Route path="/" component={HomeIndex} />
</div>
</BrowserRouter>
</Provider>
, document.querySelector('.container'));
发布于 2017-11-16 18:48:51
对axios.get()的调用是异步的。
您可能希望操作创建者返回操作对象,如下所示:
src/actions/index.js
...
export function fetchHome(result) {
return {
type: FETCH_HOME,
payload: result
}
}
然后,...and在组件中执行异步请求,并使用结果调用动作创建者:
src/components/home_index.js
...
componentDidMount() {
axios.get(`${R00T_URL}/home`, { crossdomain: true })
.then(result => {
console.log(`result: ${result}`);
this.props.fetchHome(result)
})
.catch(err => {
// Handle error
})
}
...
如果您希望将异步部分保留在操作创建者中,那么请考虑使用redux-thunk:https://www.npmjs.com/package/redux-thunk。
https://stackoverflow.com/questions/47336707
复制相似问题