react开发
安装
npm install -g create-react-app
创建项目
create-react-app react_test
cd react_test
启动
npm start
使用路由
npm install react-router-dom
增加 src/router/index.js
import Login from "../pages/Login";
import Article from "../pages/Article";
//1.hash :由react-dom中 createHashRouter创建(底层:监听hashChange事件)
//2.history:使用react-dom中 createBrowerRouter创建(底层:history对象+pushState事件)需要后端支持
import { createBrowserRouter } from "react-router-dom";
const router = createBrowserRouter([
{
path : '/login',
element : <Login></Login>
},
{
path : '/article',
element : <Article></Article>
}
])
export default router
应用入口文件渲染 src/index.js
import {createBrowserRouter,RouterProvider} from 'react-router-dom'
import router from './router';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
<RouterProvider router={router}></RouterProvider>
</React.StrictMode>
);
增加page src/Login/index.js
import { Link,useNavigate } from "react-router-dom"
const Login = () => {
const navigate = useNavigate()
return <>
<div>
login页面
<Link to="/article">跳转文章</Link>
<button onClick={()=>navigate('/article?id=1001&name=jack哈啊哈')}>跳转文章</button>
</div>
</>
}
export default Login
更改默认的端口号,在 package.json更改
在package.json中修改
"start":"react-scripts start",
为
"start":"set PORT=9000 && react-scripts start",
//mac
PORT=5000 react-scripts start
react请求接口
npm install axios
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function MyComponent() {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
try {
const response = await axios.get('https://api.example.com/data');
setData(response.data);
} catch (err) {
setError(err);
} finally {
setIsLoading(false);
}
};
fetchData();
}, []);
if (isLoading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
<h1>Data</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
export default MyComponent;
react加入antd ui
npm install antd
import React from 'react';
import { Button } from 'antd';
const App = () => {
return (
<div>
<Button type="primary">Click Me</Button>
</div>
);
};
export default App;
参考:
https://3x.ant.design/index-cn
本文来自博客园,作者:河北大学-徐小波,转载请注明原文链接:https://www.cnblogs.com/xuxiaobo/p/18606800