为您的下一个React App创建上下文

Hooks are a great way to manage state in a React Web Application. If you are familiar with hooks you are likely familiar with the useContext hook. If not this hook is very similar to the Redux library in that it can provide all components access to state. In this article, I will be discussing how to create a generalized context provider file that will allow you to abstract state logic from your components.

挂钩是在React Web应用程序中管理状态的好方法。 如果您熟悉钩子,则可能熟悉useContext钩子。 如果不是这样,则此钩子与Redux库非常相似,因为它可以为所有组件提供对状态的访问。 在本文中,我将讨论如何创建通用的上下文提供程序文件,该文件将允许您从组件中抽象状态逻辑。

The first step in creating a Context Provider is to create the file. In your file directory create a file named something like:

创建上下文提供程序的第一步是创建文件。 在文件目录中,创建一个名称如下的文件:

createDataContext.js

Now in the new file our next step is to import ‘React’ and the ‘useReducer’ hook from ‘react’

现在在新文件中,我们的下一步是从“React”中导入“React”和“ useReducer”钩子

import React, {useReducer} from 'react'

Next this file will export a function that will taken in three arguements: a reducer, actions, and an inital state. The all three of these arguements will in turn come from a specfic context file. I am not going too many details as to how to build this context file but at the end of this article I will provide a general flow for how it could look.

接下来,此文件将导出一个函数,该函数将包含三个论点:reduce,action和inital状态。 所有这三个论点将依次来自特定的上下文文件。 关于如何构建此上下文文件,我没有太多细节,但是在本文结尾,我将提供一个大致的外观。

import React, {useReducer} from 'react'export default (reducer, actions, initialState) => {}

Inside of this function we are now going to do several things first we are going to create our ‘Context’ variable by calling the ‘createContext’ function on “React”:

在此函数内部,我们现在首先要做几件事,即通过在“ React”上调用“ createContext”函数来创建“ Context”变量:

import React, {useReducer} from 'react'export default (reducer, actions, initialState) => {
const Context = React.createContext()
}

With our ‘Context’ created we can now create our ‘Provider.’ The ‘Provider’ is a React component and as all react components it will return series of JSX. This component will recevie one prop “children” which will acutally be every component that’s wrapped inside of our provider. It will also the ‘useReducer hook’ to create the state. It will also create a boundActions object which will allow our conext to be able to alter an applicaitons state.

创建“上下文”后,我们现在可以创建“提供者”。 “提供者”是一个React组件,作为所有react组件,它将返回一系列JSX。 此组件将接收一个道具“子代”,该子对象将是包装在我们提供程序内部的每个组件。 它还将使用“ useReducer挂钩”来创建状态。 它还将创建boundActions对象,该对象将使我们的conext能够更改应用程序状态。

import React, {useReducer} from 'react'export default (reducer, actions, initialState) => {
const Context = React.createContext()

const Provider = ({children}) =>{
const [state, dispatch] = useReducer(initialState)
const boundActions = {}
for (let key in actions) {
boundActions[key] = actions[key](dispatch)
}

return (
< Context.Provider value={{ state, ...boundActions }} >
{children}
</ Context.Provider >
)
}
}

Finally we just need to return our Context and Provider so that our various context files can create and export their states.

最后,我们只需要返回Context和Provider,以便我们的各种上下文文件可以创建和导出其状态。

import React, {useReducer} from 'react'export default (reducer, actions, initialState) => {
const Context = React.createContext()

const Provider = ({children}) =>{
const [state, dispatch] = useReducer(initialState)
const boundActions = {}
for (let key in actions) {
boundActions[key] = actions[key](dispatch)
}

return (
< Context.Provider value={{ state, ...boundActions }} >
{children}
</ Context.Provider >
)
} return [Context. Provider]}

With that we have completed our ‘createDataContext’ file. With one more step we can then begin accessing state within our app. Now all we need to do is import a provider (in this case ‘ExampleProvider’) and wrap it around the app in index.js:

至此,我们完成了“ createDataContext”文件。 接下来,我们可以开始在应用程序中访问状态。 现在,我们需要做的就是导入一个提供程序(在本例中为“ ExampleProvider”)并将其包装在index.js中的应用程序周围:

import React from 'react';
import ReactDOM from 'react-dom';
import {ExampleProvider} from './src/context/ExampleProvider'
import App from './App';
ReactDOM.render( <ExampleProvider>
<React>
<App />
</React>,
</ ExampleProvider>document.getElementById('root')
);

示例上下文: (Example Context:)

Below is an Example context that createds a rreducer. That reducer adds a random number id and and value to state, removes it from state, and allows for those numbers to be edited. And it also creates functions that call on each case within its reducer. Finally it exports everything by calling on createDataContext.

以下是创建rreducer的示例上下文。 减速器向状态添加随机数id和and值,将其从状态中删除,并允许编辑这些数字。 并且它还创建了在其简化器中调用每种情况的函数。 最后,它通过调用createDataContext导出所有内容。

Generic Example Context:import createDataContext from './createDataContext'const exampleReducer = (state, action) => {
switch (action.type) {
case 'edit_example':
return state.map((example) => {
return example.id === action.payload.id ? action.payload : example
})
case 'delete_example':
return state.filter((example) => example.id !== action.payload)
case 'add_example':
console.log(state)
return [
...state,
{
{
id: Math.floor(Math.random() *99999),
value: Math.floor(Math.random() *99999
}
}
]
default:
return state
}
}const addExample = (dispatch) =>{
return (title, content, callback) =>{
dispatch({type: 'add_blogpost', payload: {title, content}})
}const deleteExample = (dispatch) => {
return (id) => (
dispatch({type: 'delete_blogpost', payload: id})
)
}const editExample = (dispatch) => {
return (id, title, content, callback) => {
dispatch({
type: 'edit_blogpost',
payload: {id, title,content}
})
}export const {ExampleContext, ExampleProvider} = createDataContext(
exampleReducer,
{addExample,deleteExample,editExample },
[{id: 1, value: 1 }]
)

With this we have created an specific file which can abstract some of the logic away from creating state from each context file. Happy Coding!

这样,我们创建了一个特定的文件,该文件可以抽象一些逻辑,从而避免从每个上下文文件创建状态。 编码愉快!

翻译自: https://medium.com/swlh/ceating-context-for-your-next-react-app-9fa1670605d0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值