React创建Ts项目注意的事项

467 阅读4分钟

官方脚手架创建Ts项目

1.创建Ts和Js的区别

创建Js:npx create-react-app project

js的目录结构

image.png

创建Ts项目:npx create-react-app project --template typescript

ts的目录结构

image.png

2.Ts项目创建git仓库并提交代码

1.初始化 在本地需要关联到远程仓库的项目根目录下执行

git init

2.设置提交代码时的用户信息:

git config --global user.name "你的用户名"

git config --global user.email "你的邮箱"

3.配置ssh秘钥 项目文件夹内单击右键Git Bash Here:先输入ssh-keygen –t rsa –C "邮箱地址",一路回车,最后输入yes就生成秘钥了

image.png

4.然后关联远程仓库 [project]。你需要存在一个远程仓库,名字随意,然后执行下面的命令就可以关联到该仓库。

git remote add origin git@github.com:c55403225/ts.git

5.创建分支

`git  branch  分支名`

切换分支

git checkout 分支名

然后代码暂存到提交区

git add .

在提交到版本库

git commit -m '修改内容'

在提交到代码仓库

git push -u origin master

1.创建Ts和Js的区别

前端配置一个Mock的Api服务器

推荐使用JSON Server

1.全局安装使用 npm install -g json-server

2.创建de.json文件

3.mock一些数据

{
   “帖子”:[
    { “ id ”:1,“ title ”:“ json-server ”,“ author ”:“ typicode ” }
  ],
  “评论”:[
    { “ id ”:1,“ body ”:“一些评论”,“ postId ”:1 }
  ],
  “个人资料”:{ “姓名”: “类型代码” }
}

4.启动 JSON 服务器

json-server --watch db.json

image.png

5.请求成功

image.png

6.项目中安装JSON Server

npm install json-server -D

创建一个搜索列表得demo

一、创建基本组件

1.创建FromTable.tsx文件

import { useEffect, useState } from 'react'
import {List} from './list'
import {Search} from './Searchs'


export const FromTable = () => {

  return (
    <div>
      <List />
      <Search />
    </div>
  )
}

2.创建Serarch.tsx搜索组件

import React from 'react'

export const Search:React.FC<props> = ({users,param,setParam}) => {
  return <div>
    <input />
    <select>
      <option value="">负责人</option>
    </select>
  </div>
}

3.创建List.tsx组件

import React from 'react'

export const List:React.FC<props> = ({users,lists}) => {

  return <table>
         <thead>
         <tr>
            <th>名称</th>
            <th>负责人</th>
          </tr> 
         </thead>
          
         <tbody>
         <tr>
            <td>测试</td>
            <td>测试内容</td>
          </tr> 
         </tbody>
          
  </table>
}

二、状态提升,把子组件要用到的状态提升至父组件

4.FromTable.tsx

import { useEffect, useState } from 'react'
import {List} from './list'
import {Search} from './Searchs'

const api =process.env.REACT_APP_API_URL;
console.log(process.env,'api1')
export const FromTable = () => {
  const [param, setParam] = useState({
    name: '',
    personid: '',
  })
  const [users,setUser] =useState([])
  const [list,setList] =useState([])
  //传递加参数
  useEffect(()=>{
    // 由于param默认为空,这里传参不确定是选择查询为空的数据还是查询所有数据
    // 所以要定义一个工具函数来解决
    fetch(`${api}/list`).then(async response=>{

      if(response.ok){
         setList(await response.json())
      }
     
    })
  },[param])
  useEffect(()=>{
    fetch(`${api}/users`).then(async response=>{
      if(response.ok){
         setUser(await response.json())
      }
     
    })
  },[])
  return (
    <div style={{margin:'0 auto'}}>
      <List lists={list} users={users}/>
      <Search  param={param} setParam={setParam} users={users}/>
    </div>
  )
}

5.Search.tsx

import React from 'react'

interface props {
  users:any,
  param:any,
  setParam:Function,
}
export const Search:React.FC<props> = ({users,param,setParam}) => {
  // console.log(users,param)
  return <div>
    <input type="text" value={param.name}  onChange={event=>setParam({
      ...param,
      name:event.target.value
    })}/>
    <select value={param.personid}  onChange={event=>setParam({
      ...param,
      personid:event.target.value
    })}>
      <option value="">负责人</option>
      {
        users.map((user) =><option>{user.name}</option>)
      }
    </select>
  </div>
}

6.List.tsx

import React from 'react'

interface props{
  users:any,
  lists:any
}
export const List:React.FC<props> = ({users,lists}) => {

  return <table>
         <thead>
         <tr>
            <th>名称</th>
            <th>负责人</th>
          </tr> 
         </thead>
          
         <tbody>
         {
            lists.map((item:any)=>{
              return(
               <tr key={item.id}>
                  <td>{item.organization}</td>
                  <td>{users.find(user=>user.id===item.personId)?.name||'未知'}</td>
               </tr>
              )
            })
          } 
         </tbody>
          
  </table>
}

7.在db.json文件中制造JSON数据

"users": [
    {
      "id": "1",
      "name": "陈理鹏"
    },
    {
      "id": "2",
      "name": "李慧星"
    },
    {
      "id": "3",
      "name": "王岩"
    },
    {
      "id": "4",
      "name": "徐辉"
    },
    {
      "id": "5",
      "name": "李文博"
    },
    {
      "id": "6",
      "name": "潘星有"
    }
  ],
  "list": [
    {
      "id": "1",
      "name": "前端开发",
      "personid": "1",
      "organization": "前端开发",
      "created": "1560341853461"
    },
    {
      "id": "2",
      "name": "教师",
      "personid": "2",
      "organization": "教师",
      "created": "15616541656"
    },
    {
      "id": "3",
      "name": "前端开发",
      "personid": "3",
      "organization": "前端开发",
      "created": "1560334189106"
    },
    {
      "id": "4",
      "name": "前端开发",
      "personid": "4",
      "organization": "前端开发",
      "created": "17831145174"
    },
    {
      "id": "5",
      "name": "公务员",
      "personid": "5",
      "organization": "公务员",
      "created": "13201165148"
    },
    {
      "id": "6",
      "name": "前端开发",
      "personid": "6",
      "organization": "前端开发",
      "created": "13201165148"
    }
  ]

创建传参方法并且保证第一次为空的处理方法

1.新建until文件夹,并创建index.js文件

//判断值为0的时候不是false状态
export const isFaily = (value) => (value === 0 ? false : !value)
//定义一个清除第一次传参没有值的方法
export const clearObject = (object) => {
 //定义一个result来存储复制的objiect数组
 const result = { ...object }
 //遍历对象
 Object.keys(result).forEach((key) => {
   console.log(key, 'key')
   const value = result[key]
   if (isFaily(value)) {
     //不为0则删除
     delete result[key]
   }
 })
 return result
}

2.在FromTable组件中传参,并且qs库进行序列化

import { useEffect, useState } from 'react'
import {List} from './list'
import {Search} from './Searchs'
import *as qs from 'qs';
import {clearObject} from '../until/indedx'
const api =process.env.REACT_APP_API_URL;
console.log(process.env,'api1')
export const FromTable = () => {
  const [param, setParam] = useState({
    name: '',
    personid: '',
  })
  const [users,setUser] =useState([])
  const [list,setList] =useState([])
  //传递加参数
  useEffect(()=>{
    // 由于param默认为空,这里传参不确定是选择查询为空的数据还是查询所有数据
    // 所以要定义一个工具函数来解决
    fetch(`${api}/list?${qs.stringify(clearObject(param))}`).then(async response=>{

      if(response.ok){
         setList(await response.json())
      }
     
    })
  },[param])
  useEffect(()=>{
    fetch(`${api}/users`).then(async response=>{
      if(response.ok){
         setUser(await response.json())
      }
     
    })
  },[])
  return (
    <div style={{margin:'0 auto'}}>
      <List lists={list} users={users}/>
      <Search  param={param} setParam={setParam} users={users}/>
    </div>
  )
}

3.npm run start 运行前端代码,json-server --watch db.json --port 5000(db指的json文件,port指的是端口,个悲剧自己的文件名和要启动的端口自行调整)

image.png

4.输入框中输入时,得到输入对应的数据

image.png

image.png 5.选择下拉框时,选择展示对应的数据

image.png

image.png

一个基于react Hook的基本的list展示列表就做好了