我已经阅读了很多关于此的示例,但没有得到我的问题的结果,我想通过使用 localhost 获取 MySQL 数据库内的值,使用 PHP 进行编码并将值返回为 JSON 格式,例如
[
{"id":"7",
"name":"Sammy",
"address":"New York",
"age":"42"}
]
使用这种格式,我可以在 GetApi.js 中使用此代码来获取数据
class GetApi {
static getAllUsers() {
return fetch('http://192.168.1.199/App/show_all_data.php')
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
dispatch(itemsIsLoading(false));
return response;
})
.then((response) => response.json())
.then((items) => dispatch(itemsFetchDataSuccess(items)))
.catch(() => dispatch(itemsHasErrored(true)));
}
}
export default GetApi;
这是action.js
import GetApi from '../../api/GetApi';
export function itemsHasErrored(bool: boolean) {
return {
type: "ITEMS_HAS_ERRORED",
hasErrored: bool
};
}
export function itemsIsLoading(bool: boolean) {
return {
type: "ITEMS_IS_LOADING",
isLoading: bool
};
}
export function itemsFetchDataSuccess(items: Object) {
return {
type: "ITEMS_FETCH_DATA_SUCCESS",
items
};
}
export function itemsFetchData(url: any) {
return function(dispatch) {
return GetApi.getAllUsers().then(items => {
dispatch(itemsFetchDataSuccess(items));
dispatch(itemsIsLoading(false));
}).catch(error => {
throw(error);
});
};
}
这是reducer.js
const initialState = {
isLoading: true,
hasErrored: false,
items: []
};
export default function(state: any = initialState, action: Function) {
switch (action.type) {
case "ITEMS_HAS_ERRORED":
return { ...state, hasErrored: action.hasErrored };
case "ITEMS_IS_LOADING":
return { ...state, isLoading: action.isLoading };
case "ITEMS_FETCH_DATA_SUCCESS":
return { ...state, items: action.items };
default:
return state;
}
}
在index.js中调用action.js函数
import { itemsFetchData } from "../../actions";
...
all codings that were not related with calling action.js
...
const navigation = this.props.navigation;
let items = this.props.items;
if (items.hasOwnProperty('item')) {
items = items.item
}
return (
<List
dataArray={this.props.items}
renderRow={(
data
) =>
<ListItem icon style={styles.listitem}>
<Left>
<Text>
{data.name}
</Text>
</Left>
<Right>
<Text>
{data.address}
</Text>
</Right>
</ListItem>}
/>
);
function bindAction(dispatch) {
return {
fetchData: url => dispatch(itemsFetchData(url))
};
}
const mapStateToProps = state => ({
items: state.homeReducer.items,
hasErrored: state.homeReducer.hasErrored,
isLoading: state.homeReducer.isLoading
});
export default connect(mapStateToProps, bindAction)(ShowData);
当我运行代码时没有得到任何结果,它只是显示了加载图标。即使我设置 isLoading:false,主菜单也会显示,但没有数据
我只是想尽量减少 index.js 中的代码,因为这里发布的代码太长了。如果有必要,我会在下一条评论中这样做。
最佳答案
我建议使用 Epips ,下面是供您遵循的示例链接。
您可以查看来自 epic 的操作和数据 ajax 调用以及它如何连接回操作。
注意:这里使用的是axios而不是fetch api...
关于javascript - 如何使用 React 从 action.js 中的 API 获取响应值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48496312/