我应该使用redux吗

Starting a new application means drawing out a blueprint of what you want it to look like, and thinking about how you are going to implement whatever you are going to do before you even write any code. As a JavaScript developer, I often find myself questioning whether or not I’ll need to use Redux.

启动一个新的应用程序意味着绘制出您想要它的外观的蓝图,并在编写任何代码之前考虑如何实现将要执行的操作。 作为一名JavaScript开发人员,我经常发现自己在质疑是否需要使用Redux。

Redux is a state management technology created by the React team. It cleans up your application’s state massively by creating a global “store” where all state and state changes can be held, regardless of which file or page you’re in. Redux also helps developers steer clear of prop drilling, as parent components no longer need to directly pass downstate to their children, grandchildren, great-grandchildren, etc. via props. Let’s take a look at what this means through a create-user instance.

Redux是一种由React团队创建的状态管理技术。 它通过创建一个全局“存储”来大规模清理应用程序的状态,无论您位于哪个文件或页面中,所有状态和状态的更改可以保存在其中,Redux还可以帮助开发人员避开prop钻探,因为父组件不再需要通过道具直接将低级状态传给其子女,孙子女,曾孙子女等。 让我们看看通过创建用户实例这意味着什么。

First, we’ll need a sign-up form in order for our user to create an account.

首先,我们需要一个注册表格,以便我们的用户创建一个帐户。

// src/Components/SignupForm.js //import {createUser} from '../Actions/userActions.js'
import React from 'react'
import {connect} from 'react-redux'class SignupForm extends React.Component{

state = {
username: '',
password: '',
} handleChange = e => {
this.setState({
[e.target.name]: e.target.value
})
} handleSubmit = e => {
e.preventDefault()
this.props.createUser(this.state)
} render(){
return(
<form onSubmit={this.handleSubmit}>
<input type="text" name="username"
placeholder="Username"
value={this.state.username}
onChange={this.handleChange}/>
<input type="password" name="password"
placeholder="Enter Password"
value={this.state.password}
onChange={this.handleChange}/>
<input type="submit" value="Signup"/>}
</form>
)
}
}export default connect(null, createUser)(SignupForm)

Let’s go through this and see where Redux has been inserted into our React form.

让我们看一看,看看Redux已插入到我们的React表单中的位置。

import {createUser} from '../Actions/userActions.js'

This createUser business is an action that we’ve created in a file called userActions.js, and we’re importing it into our SignupForm.js file. Since we imported it, we now have access to this method. Next up:

此createUser业务是我们在名为userActions.js的文件中创建的操作,并将其导入到SignupForm.js文件中。 自导入以来,我们现在可以使用此方法。 接下来:

import {connect} from 'react-redux'

Let’s start from ‘react-redux’. As the documentation says:

让我们从“ react-redux”开始。 如文档所述

React Redux is the official React binding for Redux. It lets your React components read data from a Redux store, and dispatch actions to the store to update data.

React终极版是官方的React结合终极版。 它使您的React组件可以从Redux存储中读取数据,并向存储分派操作以更新数据。

Let’s break that second sentence down a bit. The first part of it is saying that by importing tools from the React Redux library, such as Connect, we give our React components access to everything in the Redux store. That means global state and actions as well. In order to bind the Redux store to your React components, you must:

让我们将第二句话分解一下。 它的第一部分是说,通过从React Redux库中导入工具(例如Connect),我们使React组件可以访问Redux存储中的所有内容。 这也意味着全球状态和行动。 为了将Redux存储绑定到您的React组件,您必须:

export default connect(null, createUser)(SignupForm)

The first argument in Connect is null. That’s because we aren’t giving this component any state from the global store. We’ll go through an example of giving a React component state from the global store later. For now, we must leave it as null, since connect is expecting there to at least be a function which will give state to this component’s properties. If we just had our createUser action in there without null, it would be very, very confused.

Connect中的第一个参数为null。 这是因为我们没有从全局存储中为该组件提供任何状态。 稍后,我们将通过一个示例来提供全局存储中的React组件状态。 现在,我们必须将其保留为null,因为connect期望至少有一个函数可以为该组件的属性提供状态。 如果我们只在其中有没有null的createUser动作,那将会非常混乱。

Actions are the bread and butter here. They give our application the information that our reducer will need to modify state. We are calling our createUser action in our React component in this line of code:

行动就是这里的面包和黄油。 它们为我们的应用程序提供了减速器修改状态所需的信息。 我们在以下代码行中的React组件中调用createUser操作:

this.props.createUser(this.state)

This is sending the state (AKA, the user object we just created through this form), to our userActions file. Before we move on: in order to give your React component access to an action, you must:

这会将状态(也就是我们刚刚通过此表单创建的用户对象)发送到我们的userActions文件。 在继续之前:为了使您的React组件可以访问某个动作,您必须:

  1. Import the action from its respective file

    从其各自的文件导入动作
  2. Import Connect from React Redux

    从React Redux导入Connect
  3. Export & Connect your function or class as written above

    如上所述导出并连接您的函数或类

Our infamous createUser action will look like this:

我们臭名昭著的createUser操作将如下所示:

// src/Actions/userActions.js //export const createUser = (userObj) => {
return (dispatch) => {
fetch('http://localhost:3000/users', {
method: 'POST',
headers: {
'accepts': 'application/json',
'content-type': 'application/json'
},
body: JSON.stringify(userObj)
})
.then(response => response.json())
.then(data => {
dispatch({type: 'CREATE_USER', payload: data})
})
}
}

Yep, nothing special… for the most part. It looks like a normal fetch call, except what’s this dispatch business?

是的,没什么特别的...大部分情况下。 看起来像是正常的提取调用,除了此调度业务是什么?

Redux allows us to deal with asynchronous fetching by giving us a middleware tool: Thunk. In order to deal with these asynchronous fetchings, we must give our actions dispatches internally. In essence, Thunk gives us access to dispatch, which gives us access to asynchronosity in our app. If we were to be authenticating our user, we would also have a dispatch pointing to a type of ‘SHOW_ERROR’ with a payload of whatever the error message is in the case that there was an error with the POST request. For now, life is good and we don’t have to worry about authentication, and we only need one dispatch:

Redux通过提供一个中间件工具Thunk,使我们能够处理异步获取。 为了处理这些异步获取,我们必须在内部给动作分配。 本质上,Thunk允许我们访问调度,这使我们可以访问应用程序中的异步性。 如果我们要对用户进行身份验证,那么在POST请求出错的情况下,我们还将拥有一个指向有效载荷类型为'SHOW_ERROR'的调度程序,无论该错误消息是什么。 现在,生活是美好的,我们不必担心身份验证,只需要执行一次调度即可:

dispatch({type: 'CREATE_USER', payload: data})

This calls on our user reducer, which is going to modify our app’s global state.

这需要我们的用户reducer,它将修改我们应用程序的全局状态。

// src/Reducers/userReducer.js //defaultState = {currentUser: {}}export function userReducer(state = defaultState, action){
switch (action.type) {
case 'CREATE_USER':
return {
...state, state.currentUser: action.payload
}
default:
return state;
}
}

Here, our application sees that our action’s type is ‘CREATE_USER’, so it passes the data (our newly created user from our fetch call, stored in payload) to the userReducer’s ‘CREATE_USER’ case, where our state is modified to be equal to the user who just created an account. We can now tell any of our React components about this new user by mapping state to props. Let’s give it to Profile for now:

在这里,我们的应用程序看到我们的操作的类型为'CREATE_USER',因此它将数据(我们从fetch调用中创建的新用户,存储在有效负载中)传递给userReducer的'CREATE_USER'案例,其中我们的状态被修改为等于刚创建帐户的用户。 现在,我们可以通过将状态映射到prop来告诉我们的任何React组件有关此新用户的信息。 现在让我们将其提供给Profile:

// src/Profile.js //import React from 'react'
import {connect} from 'react-redux'class Profile extends React.Component{
render(){
return(
<h1>{this.props.currentUser.username}</h1>
)
}
} const mapStateToProps = state => {
return {currentUser: state.currentUser}
} export default connect(mapStateToProps)(Profile)

Our Profile now has access to our currentUser and is able to print to the screen in an h1 tag the currentUser’s username. You’ll notice our friend Connect has yet again been imported from React Redux. Now, instead of giving us access to a specific action, it’s giving us currentUser from our global Redux store. Where the first argument in our prior example for Connect was null, now it’s the function mapStateToProps, which is giving our React component, Profile, the prop of currentUser.

现在,我们的个人资料可以访问currentUser,并且可以在h1标签中将currentUser的用户名打印到屏幕上。 您会发现我们的朋友Connect再次从React Redux导入。 现在,不是让我们访问特定操作,而是从我们的全局Redux存储中为我们提供currentUser。 在先前示例中Connect的第一个参数为null的地方,现在是函数mapStateToProps,它为我们的React组件Profile提供了currentUser的支持。

So, should I use Redux? If you’re going to be using a piece of information in multiple components, yes. It’ll clean up your code and make it easier for you to access information anywhere. However, beware of your asynchronous actions and make sure you know what’s going on in your application at all times.

那么,我应该使用Redux吗? 如果您要在多个组件中使用一条信息,可以。 它将清理您的代码,并使您可以更轻松地在任何地方访问信息。 但是,请注意异步操作,并确保您始终了解应用程序中正在发生的事情。

That being said, if an application of my own had one parent that needed to pass down props to just one generation, I probably would stick to using React state. And, of course, you can always use both forms of state in the same application, given the right circumstances.

话虽这么说,如果我自己的应用程序有一个父代需要将props传递给一代,那么我可能会坚持使用React状态。 而且,当然,在适当的情况下,您始终可以在同一应用程序中同时使用两种状态。

翻译自: https://medium.com/swlh/should-i-use-redux-d563f378bbbe

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
UmijS 是一个基于 React 的前端开发框架,它提供了一种简单易用的方式来构建单页应用程序。如果你想在 UmiJS 中使用 Redux,可以按照以下步骤进行操作: 1. 安装 Redux 和 React-Redux:在你的项目目录下运行以下命令来安装所需的依赖包: ``` npm install redux react-redux --save ``` 2. 创建 Redux store:在你的项目中创建一个 `store.js` 文件,并使用 Redux 的 `createStore` 方法来创建一个 Redux store。例如: ```javascript import { createStore } from 'redux'; import rootReducer from './reducers'; // 导入你的根reducer const store = createStore(rootReducer); export default store; ``` 3. 创建 reducers:在你的项目中创建一个 `reducers.js` 文件,用于定义你的 reducers。例如: ```javascript // 定义初始状态 const initialState = { // 初始状态数据 }; // 定义 reducer const rootReducer = (state = initialState, action) => { switch (action.type) { // 处理不同的 action 类型,更新 state default: return state; } }; export default rootReducer; ``` 4. 使用 Redux Provider:在你的根组件中使用 Redux 的 `Provider` 组件,将 Redux store 传递给 UmiJS 应用程序。例如: ```javascript import { Provider } from 'react-redux'; import store from './store'; export function rootContainer(container) { return React.createElement(Provider, { store: store }, container); } ``` 5. 在组件中使用 Redux使用 `react-redux` 提供的 `connect` 方法来连接你的组件到 Redux store,并将需要的 state 和 action 传递给组件。例如: ```javascript import { connect } from 'react-redux'; function MyComponent(props) { // 使用 props 中的 state 和 action // ... } const mapStateToProps = state => { // 将需要的 state 映射到组件的 props return { // ... }; }; const mapDispatchToProps = dispatch => { // 将需要的 action 映射

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值