Skip to main content

一步步,带你简单体验全栈开发(-)

· 5 min read
bigBlack

目标:写个页面

在这个指南中,我们将一步步地进行React全栈开发,目标是创建一个简单的页面。我们将探讨环境配置、页面编写、页面间的导航和参数传递、组件间的通信以及接口请求等关键步骤。

第一步,配置环境

在进行React全栈开发之前,首先需要配置开发环境。我们将使用React及其生态中的一些关键库,例如react-domnest。以下是配置环境的基本步骤:

代码示例:package.json

{
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"nest": "^x.x.x"
// 其他依赖
},
"scripts": {
"start": "your-start-script",
// 其他脚本
}
}

代码示例:babel.config.js

module.exports = {
presets: ['@babel/preset-env', '@babel/preset-react'],
};

第二步,写个页面

一旦环境配置完成,我们可以开始编写我们的第一个页面。这将涉及到创建React组件以及使用一些基本的UI元素。

代码示例:src/pages/Home.js

import React from 'react';

const Home = () => {
return (
<div>
<h1>Welcome to our React Full-Stack Blog</h1>
<p>This is the home page of our application.</p>
</div>
);
};

export default Home;

第三步,页面跳转传参

为了使我们的应用更加交互,我们将探讨页面之间的导航和参数传递。

1. 两种路由导航写法

在React中,有多种方式可以实现路由导航。我们将研究两种常用的方法。

代码示例:使用React Router进行导航
npm install react-router-dom
import { BrowserRouter as Router, Link, Route } from 'react-router-dom';

const App = () => {
return (
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Router>
);
};
代码示例:使用history进行导航
import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

const navigateTo = (url) => {
history.push(url);
};

// 使用
navigateTo('/about');

2. 三种路由参数获取方法

在React中,获取路由参数有多种方式,我们将讨论其中的三种方法。

代码示例:使用useParams Hook
import { useParams } from 'react-router-dom';

const BlogPost = () => {
const { postId } = useParams();

return <p>Displaying blog post #{postId}</p>;
};
代码示例:使用withRouter HOC
import { withRouter } from 'react-router-dom';

const BlogPost = (props) => {
const { match } = props;
const postId = match.params.postId;

return <p>Displaying blog post #{postId}</p>;
};

export default withRouter(BlogPost);
代码示例:使用useLocation Hook
import { useLocation } from 'react-router-dom';

const BlogPost = () => {
const location = useLocation();
const postId = location.pathname.split('/').pop();

return <p>Displaying blog post #{postId}</p>;
};

第四步,组件间通信

在React开发中,组件间通信是一个关键的主题。我们将讨论父子组件通信、兄弟组件通信以及爷孙组件通信(跨组件通信)。

1. 父子组件通信

在React中,通过props可以实现父子组件之间的通信。

代码示例:父组件传递数据给子组件
// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
const data = 'Data from parent';

return <ChildComponent data={data} />;
};

// ChildComponent.js
import React from 'react';

const ChildComponent = (props) => {
const { data } = props;

return <p>Data received from parent: {data}</p>;
};

export default ChildComponent;

2. 兄弟组件通信

为了实现兄弟组件之间的通信,可以通过共享状态或者使用父组件作为中介。

代码示例:使用父组件作为中介
// ParentComponent.js
import React, { useState } from 'react';
import BrotherComponentA from './BrotherComponentA';
import BrotherComponentB from './BrotherComponentB';

const ParentComponent = () => {
const [sharedData, setSharedData] = useState('');

return (
<>
<BrotherComponentA setSharedData={setSharedData} />
<BrotherComponentB sharedData={sharedData} />
</>
);
};

// BrotherComponentA.js
import React from 'react';

const BrotherComponentA = (props) => {
const { setSharedData } = props;

const handleChange = (e) => {
setSharedData(e.target.value);
};

return <input type="text" onChange={handleChange} />;
};

// BrotherComponentB.js
import React from 'react';

const BrotherComponentB = (props) => {
const { sharedData } = props;

return <p>Data shared between brothers: {sharedData}</p>;
};

export { BrotherComponentA, BrotherComponentB };

3. 爷孙组件通信(跨组件通信)

对于爷孙组件之间的通信,可以使用Context API或者第三方状态管理工具,如Redux。

第五步,接口请求

在现代的Web应用中,与后端进行数据交互是不可避免的。我们将讨论如何在React

中进行接口请求。

代码示例:使用fetch进行简单的接口请求

import React, { useState, useEffect } from 'react';

const ApiExample = () => {
const [data, setData] = useState([]);

useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((data) => setData(data))
.catch((error) => console.error('Error fetching data:', error));
}, []);

return (
<div>
<h2>API Example</h2>
<ul>
{data.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</div>
);
};

export default ApiExample;

总结

在这篇React全栈开发实践指南中,我们覆盖了从环境配置到页面编写、导航、组件通信以及接口请求的各个方面。通过这些实例,希望读者能够建立起对React全栈开发的整体认识,并能够在实际项目中灵活运用这些技术。

以上示例代码仅为演示目的,实际项目中可能需要根据具体情况进行调整和优化。希望这篇指南对你在React全栈开发中的学习和实践有所帮助。