javascript - 如何使用 React 从 action.js 中的 API 获取响应值

标签 javascript node.js reactjs react-native

我已经阅读了很多关于此的示例,但没有得到我的问题的结果,我想通过使用 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 Example

您可以查看来自 epic 的操作和数据 ajax 调用以及它如何连接回操作。

注意:这里使用的是axios而不是fetch api...

关于javascript - 如何使用 React 从 action.js 中的 API 获取响应值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48496312/

相关文章:

javascript - 如何在jQuery函数执行时显示加载进度条?

node.js - 如何对多个主机名使用同一个 Express session ?

javascript - 从 React 组件中的脚本访问变量

javascript - XmlHttpRequest 上传在两次使用之间暂停后挂起

javascript - 如何注册来自不同子域的服务 worker

javascript - Passport.js 无状态

node.js - 如何打破 `then` 函数中的 promise

由于一个页面上的 MIME 类型,CSS 无法加载,但在另一个页面上工作正常

javascript - 在 React.js 中的组件之间传递消息

reactjs - 为 react-admin 仪表板推荐一个拖放库?