剧场模式
首页前端Reactreact 基础实践篇-小型财务系统

react 基础实践篇-小型财务系统 #5 静态类型检查和改造 API url

海外散仙厉飞雨 · 真仙发布于
4

注意:当运行 yarn start 的时候,要传环境变量的时候,视频中没有提到过 windows 的情况, windows 传环境变量应该类似下面这么做:

windows平台:不能直接使用环境变量, 步骤如下:

  1. npm install cross-env --save-dev

  2. 命令改为

"start": "cross-env REACT_APP_RECORDS_API_URL=https://5a637781f2bae00012ca1a18.mockapi.io/api/v1/records react-scripts start"

环境变量问题,如果实在解决不了,就建议写死地址就好了,用上面的地址就可以,不用考虑太多,跳过

https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-custom-environment-variables

诱人的 react 视频教程 - 基础篇 #6 通过 Props 传递数据: https://www.rails365.net/movies/you-ren-de-react-shi-pin-jiao-cheng-ji-chu-pian-6-tong-guo-props-chuan-di-shu-ju

src/utils/RecordsAPI.js

import axios from 'axios';
const api = process.env.REACT_APP_RECORDS_API_URL || "https://5a54227777e1d20012fa0723.mockapi.io"

export const getAll = () =>
  axios.get(`${api}/api/v1/records`)

.env.development.local

REACT_APP_RECORDS_API_URL=https://5a54227777e1d20012fa0723.mockapi.io

src/components/Record.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class Records extends Component {
  render() {
    return (
      <tr>
        <td>{this.props.date}</td>
        <td>{this.props.title}</td>
        <td>{this.props.amount}</td>
      </tr>
    );
  }
}

Records.propTypes = {
  id: PropTypes.number,
  date: PropTypes.string,
  title: PropTypes.string,
  amount: PropTypes.number
}

src/components/Records.js

import React, { Component } from 'react';
import Record from './Record';
import * as RecordsAPI from '../utils/RecordsAPI'

class Records extends Component {
  constructor() {
    super();
    this.state = {
      error: null,
      isLoaded: false,
      records: []
    }
  }

  componentDidMount() {
    RecordsAPI.getAll().then(
      response => this.setState({
        records: response.data,
        isLoaded: true
      })
    ).catch(
      error => this.setState({
        isLoaded: true,
        error
      })
    )
  }

  render() {
    const { error, isLoaded, records } = this.state;

    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div>
          <h2>Records</h2>
          <table className="table table-bordered">
            <thead>
              <tr>
                <th>Date</th>
                <th>Title</th>
                <th>Amount</th>
              </tr>
            </thead>
            <tbody>
              {records.map((record) => <Record key={record.id} {...record} />)}
            </tbody>
          </table>
        </div>
      );
    }
  }
}

export default Records;
21 条回复

© 汕尾市求知科技有限公司 | 粤ICP备19038915号 | 在线学员:32

Top