react-native - 未从 API 获取数据
问题描述
我正在尝试在 localhost 上使用 React Native 和 Redux 从 API 获取数据,但它没有获取,并且显示此错误:“TypeError: Can not convert undefine or null to an object”
这是我的代码:
应用程序.js
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import reducers from './reducers';
import Router from './Router';
class App extends Component {
render() {
const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
return (
<Provider store={store}>
<Router />
</Provider>
);
}
}
export default App;
减速器/RestaurantList.js
import { RESTAURANT_SHOW } from '../actions/types';
const INITIAL_STATE = {
restaurant: ''
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case RESTAURANT_SHOW:
return {
...state,
restaurant: action.payload.data
};
default:
return state;
}
};
动作/RestaurantShow.js
import { RESTAURANT_SHOW } from './types';
import axios from 'axios';
export const restaurantShow = () => {
return (dispatch) => {
dispatch({
type: RESTAURANT_SHOW,
payload: { data: response.data }
})
return axios.post('http://MY IP ADDRESS/react/restaurant.php')
//.then((response) => {
// Actions.main({ resdata: response.data });
// })
.then((response)=> {
(dispatch(getRestaurant(response.data)))
})
.catch((error) => {
console.log(error);
});
}
}
export function getRestaurant(data) {
return {
type: RESTAURANT_SHOW,
data
}
}
组件/Restaurant.js
import React, {Component} from 'react';
import { View,StyleSheet, Image, ListView, Text, ScrollView} from 'react-native';
import {connect} from "react-redux";
import {SearchBox, CardSection} from './common'
import * as actionCreators from "../actions/index.js";
class Restaurant extends Component{
componentWillMount() {
this.createDataSource(this.props);
}
componentWillReceiveProps(nextProps) {
this.createDataSource(nextProps);
console.log(this.props.id);
}
createDataSource({ resdata }) {
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
this.dataSource = ds.cloneWithRows(resdata);
}
render(){
console.log(this.props);
return(
<ScrollView>
<SearchBox />
<View style={styles.MainContainer}>
<ListView
dataSource={this.dataSource}
renderRow={(rowData) =>
<View style={{flex:1, flexDirection: 'column'}} >
<CardSection>
<Text style={styles.text}>{rowData.name}</Text></CardSection>
</View> }
/>
</View>
</ScrollView>
);
}
}
const mapStateToProps = state => {
return state
};
export default connect (mapStateToProps, actionCreators)(Restaurant);
这是模拟器中的错误截图
解决方案
推荐阅读
- java - 如何使用顺序搜索在数组中找到相应的负值?
- c++ - 在 vulkan 光线追踪中让 uvs 正常工作时遇到一些问题
- sql - Sql 创建新行并更新关联值
- observable - 为什么必须在 `single` 之前调用 `toBlocking`?
- javascript - 当内容滚动到视图中时激活动画
- android - registerForActivityResult 在选择浏览其他应用程序中的文件后返回空的结果列表
- javascript - 使用循环数据 json 值并将每个值显示到卡片中
- javascript - MySQL 连接仅使用 PHP 被拒绝,Javascript 正在我的服务器上运行
- sas - 将一个表拆分为三个表
- swift - 在 int swift 的数组上找到最大的三个数字