【发布时间】:2017-11-17 02:55:12
【问题描述】:
我正在做我的第一个 react.js 应用程序。由于 Visual Studio 2017 中的 react 和 redux 模板项目存在一些问题,我最终在 Visual Studio 2017 中使用了一个 Web API,并在 Visual Studio Code 中使用了一个完全不同的 react 项目(我不知道这是否相关)。我正在尝试使用我的 Web API,但我的 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'));
【问题讨论】:
-
与其只返回
return action.payload.data,不如返回一个新的状态return { ...state , action.payload.data}并尝试不使用“未定义”,因为它将返回默认状态,这将导致返回相同的状态
标签: reactjs cross-domain axios