创建一个redux项目
时间: 2023-07-20 10:36:25 浏览: 196
好的,下面是创建一个基本的 Redux 项目的步骤:
1. 首先,你需要在本地安装 Node.js 和 npm。
2. 打开终端并创建一个新的项目文件夹:
```bash
mkdir my-redux-app
cd my-redux-app
```
3. 初始化 npm 项目并安装必要的依赖:
```bash
npm init -y
npm install redux react-redux redux-thunk
```
4. 创建一个 `src` 文件夹和一个 `index.js` 文件:
```bash
mkdir src
touch src/index.js
```
5. 在 `index.js` 文件中导入 Redux 库并创建一个 store:
```javascript
import { createStore } from 'redux';
const initialState = {};
const reducer = (state = initialState, action) => {
switch (action.type) {
default:
return state;
}
};
const store = createStore(reducer);
```
6. 在 `index.js` 文件中渲染 React 应用并将 store 传递给应用:
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
```
7. 创建一个 `App.js` 文件并编写 React 组件:
```javascript
import React from 'react';
import { connect } from 'react-redux';
const App = ({ state }) => {
return (
<div>
<h1>Hello, Redux!</h1>
<pre>{JSON.stringify(state, null, 2)}</pre>
</div>
);
};
const mapStateToProps = (state) => {
return {
state,
};
};
export default connect(mapStateToProps)(App);
```
8. 在 `index.html` 文件中创建一个根节点:
```html
<!DOCTYPE html>
<html>
<head>
<title>My Redux App</title>
</head>
<body>
<div id="root"></div>
<script src="./dist/bundle.js"></script>
</body>
</html>
```
9. 使用 webpack 或者其他打包工具将项目打包成一个 `bundle.js` 文件。
10. 在终端中运行应用:
```bash
npm start
```
以上是创建一个基本的 Redux 项目的步骤,你可以根据需要进行修改和扩展。
阅读全文
相关推荐


















