精华内容
下载资源
问答
  • useReducer

    2021-04-02 19:43:21
    import React, { useReducer } from "react"; // useReducer的作用 // 根据不同的场景,对state做不同的处理 function reducer(state, action) { switch (action.type) { case "increment": return { ...state, ...

    代码:

    import React, { useReducer } from "react";
    
    // useReducer的作用
    // 根据不同的场景,对state做不同的处理
    function reducer(state, action) {
      switch (action.type) {
        case "increment":
          return { ...state, count: state.count + action.payload };
        case "decrement":
          return { ...state, count: state.count - action.payload };
        case "sayHello":
          return { ...state, hello: "hello world" };
        default:
          throw new Error();
      }
    }
    
    function UseReducerDemo() {
      const [state, dispatch] = useReducer(reducer, { count: 1 });
      return (
        <div>
          <div>数值:{state.count}</div>
          <div>{state.hello}</div>
          <button
            onClick={() => {
              dispatch({ type: "increment", payload: 10 });
            }}> +10</button>
          
          <button
            onClick={() => {
              dispatch({ type: "decrement", payload: 10 });
            }}>-10</button>
          <button
            onClick={() => {
              dispatch({ type: "sayHello" });
            }}> sayHello</button>
        </div>
      );
    }
    
    export default UseReducerDemo;
    

    结果:
    在这里插入图片描述

    展开全文
  • useReducer support

    2020-11-26 15:35:54
    <p>I think it would be really cool if we could use redux sauce with the hook method useReducer <p>Would this ever be possible? </p><p>该提问来源于开源项目:jkeam/reduxsauce</p></div>
  • useReducer-源码

    2021-03-21 02:10:54
    React以运行项目。 1.克隆此仓库 2.cd useReducer。 3.运行纱线安装。 4.运行纱线启动。
  • usereducer 异步React’s useReducer brings us one step closer to replacing ReduxStore with basic react hooks. Now creating a store and dispatch function is as easy as calling useReducer with your ...

    usereducer 异步

    React’s useReducer brings us one step closer to replacing ReduxStore with basic react hooks. Now creating a store and dispatch function is as easy as calling useReducer with your reducer function and initial state object.

    React的useReducer使我们比用基本的React钩子替换ReduxStore更近了一步。 现在,创建存储和调度函数就像使用reducer函数和初始状态对象调用useReducer一样容易。

    const [state, dispatch] = useReducer(reducer, initialState)

    But what about async actions? Redux allows you to pass functions to your dispatch that will be invoked with your dispatch object.

    但是异步动作呢? Redux允许您将函数传递给调度 ,该函数将与调度对象一起调用。

    dispatch((dispatch) => {
    someAsyncOperation((result) => {
    dispatch({ type: 'UPDATE_RESULT', payload: result })
    }
    })

    You can use the thunk pattern to if you’d like to pass arguments to your async operation.

    如果要将参数传递给异步操作,则可以使用thunk模式

    function thunk(someArg: string) {
    return function(dispatch: Dispatch<ActionType>) {
    someAsyncOperation(someArg, (result) => {
    dispatch({ type: 'UPDATE_RESULT', payload: result })
    }
    }
    }dispatch(thunk("foo"))

    It’s a nice pattern, but it doesn’t work with the out-of-the-box dispatch we get with useReducer. So how do we achieve the same effect without Redux?

    这是一个很好的模式,但不适用于我们通过useReducer获得的现成的分派。 那么,如何在没有Redux的情况下实现相同的效果?

    Let’s keep it simple. Use a utility function like this.

    让我们保持简单。 使用这样的实用程序功能。

    Pass the original dispatch returned from useReducer into our wrapAsync utility function. It will return a function that serves as a proxy for the original dispatch and invokes the dispatched action if it happens to be a function. The T generic here is inferred from the action type of your dispatch. Here’s how it looks in action:

    useReducer返回的原始调度useReducer到我们的wrapAsync实用程序函数中。 它将返回一个充当原始调度的代理的函数,并在恰好是一个函数的情况下调用调度的动作。 这里的T泛型是根据调度的操作类型推断的。 实际效果如下:

    const [state, dispatch] = useReducer(reducer, initialState)
    const asyncDispatch = wrapAsync(dispatch)asyncDispatch((dispatch) => dispatch({ /* Action */ }))

    But wait- one last thing. We’re currently generating a new wrapped dispatch object on every render but we shouldn’t need to call wrapAsync() again unless the original dispatch object returned from useReducer changes. We’ll use another basic react hook for this:

    但是,等等-最后一件事。 当前,我们在每个渲染器上都生成一个新的包装的分发对象,但是除非从useReducer返回的原始分发对象发生更改,否则我们无需再次调用wrapAsync() 。 我们将为此使用另一个基本的react钩子:

    const [state, dispatch] = useReducer(reducer, initialState)
    const asyncDispatch = useMemo(() => wrapAsync(dispatch), [dispatch])

    The dependency array in useMemo here ensures that we only need to call wrapAsync if the original dispatch changes.

    此处useMemo的依赖关系数组可确保仅在原始调度发生更改时才需要调用wrapAsync。

    That’s it. You could of course extract this into a custom useAsyncReducer hook if you wanted to- but that’s up to you. You could also use a promise version of the async dispatch, here’s a promise version of the util function. Hope this helps!

    而已。 当然,如果愿意,您可以将其提取到自定义useAsyncReducer挂钩中,但这取决于您。 您还可以使用异步调度的Promise版本,这是util函数的Promise版本。 希望这可以帮助!

    type AsyncDispatch<T> = Dispatch<T | Promise<T>>
    
    
    function wrapAsync<T>(dispatch: Dispatch<T>): AsyncDispatch<T> {
      return (action: T | Promise<T>) => {
        if (action instanceof Promise) {
          return action.then(dispatch)
        }
        return dispatch(action)
      }
    }

    翻译自: https://medium.com/@joseph.michael.sample/async-actions-with-usereducer-d75a2c5dc55c

    usereducer 异步

    展开全文
  • Fix useReducer example

    2021-01-12 15:35:04
    <div><p>The <code>useReducer</code> <a href="https://reactjs.org/docs/hooks-reference.html#usereducer">example</a> is broken, here is a before and after codesandbox of the code example change included...
  • react useReducer

    2020-07-06 09:17:33
    我们要修改下,将单一组件的状态提取...import React, { useReducer } from 'react' //此时state 就是 count function countReducer(state, action) { // 这里写法都是标准写法! // 我去上趟茅坑,回头接着写。。..

    我们要修改下,将单一组件的状态提取出来,

    提取成为全局的组件状态,方便各个组件使用!

    为了测试这个东西,我们的设计是这样的,计数器

    count 一个组件加,一个组件减

    Cart 里面加

    这个时候用到了reducer

    import React, { useReducer } from 'react'
    //此时state 就是 count 
    function countReducer(state, action) {
        // 这里写法都是标准写法!
        // 我去上趟茅坑,回头接着写。。。
        // todos ...
        // 接着写,蚊子咬死我了,你知道的,夏天蚊子很多
        switch (action.type) {
            case "add":
                state++;
                return state;
                break;//论理说不会走到该语句,但是你写也没错啊,费代码,增加些数量,
            // 按照代码行数给钱!我发现现在做建筑的都喜欢挖坑,专门赚浮浅,死的快 
            //没有一个做大的!质量不行,把别人当傻子,最后也成为傻子,不扯了,我们继续写我们的代码
            case "minus":
                state--;
                return state;
                break;
            default:
                return state;
        }
    }
    
    
    
    const Cart = () => {
        const [state, dispatch] = useReducer(countReducer, 0);
        return (
            <div>
                <p> {state} </p>
                <button onClick={() => { dispatch({ type: "add" }) }}>+</button>
                <Hello state={state} dispatch={dispatch}></Hello>
            </div>
        );
    };
    
    // hello 里面减少
    //hello 组件
    const Hello = ({ state, dispatch }) => {
        return (
            <div>
                <p> {state} </p>
                <button onClick={() => { dispatch({ type: "minus" }) }}>-</button>
            </div>
        );
    };
    
    export default Cart;

    上面代码很简单,但是初学者很容易写错

    报如下错误

     

    展开全文
  • ReactHooks useReducer

    2021-04-09 19:45:15
    import React, { useReducer } from 'react'; function ReducerDemo(){ const [count , dispatch] = useReducer((state,action)=>{ switch(action){ case 'add': return state+1 case 'sub':

    计数器的增加功能

    import React, { useReducer } from 'react';
    
    function ReducerDemo(){
        const [count , dispatch] = useReducer((state,action)=>{
            switch(action){
                 case 'add':
                    return state+1
                 case 'sub':
                    return state-1
                 default:
                    return state
         }
        },0)//0为初始化的state
        return (
            <div>
                <h2>现在的分数是{count}</h2>
                <button onClick={()=>{dispatch('add')}}>Increment</button>
                <button onClick={()=>{dispatch('sub')}}>Decrement</button>
            </div>
        )
    }
    export default ReducerDemo
    

    useReducer第一个参数为一个reducer函数,即为作用state的函数,第二个函数为初始化的state。

    第一个参数为reducer函数,dispatch将值传入进reducer。

    展开全文
  • react hooks useReducer

    2020-02-18 08:18:33
    import React, { useReducer } from 'react'; function ReducerDemo(){ const [ count , dispatch] =useReducer((state,action)=>{ //判断action类型 switch(action){ case 'add':...
  • <div><p>added this third argument to useReducer so it can be used in the same manner as the example here: https://reactjs.org/docs/hooks-reference.html#usereducer </p><p>该提问来源于开源项目:...
  • 七、学习useReducer

    2021-02-18 23:06:32
    一、什么是useReducer? ​ useReducer是react hooks中提供的一个高级hooks,即便没有这些高级hooks,只用useState、useEffect和useContext,也能完成需求。但是这些高级的hooks可以让我们的代码具有更好的可读性、...
  • 合并多个useReducer

    2021-01-31 18:53:46
    多个useReducer的合并方法 首先创建一个store文件,在store文件下创建存放仓库state状态文件夹和存放reducer方法的文件夹 将存放store和reducer的文件进行一个合并 这里我将多个state和多个reducer分成多个文件方式...
  • <div><p>Have we discussed using <code>useReducer</code> instead of <code>useState</code> with an object for this? For this specific form it's OK, but if we had more fields maybe <code>useReducer...
  • React的useReducer 的用法

    千次阅读 2020-02-28 21:39:31
    React 的useReducer 的用法 const [state, dispatch] = useReducer(reducer, init); 当我们的 useEffect 里面涉及到两个变量的时候,我们就可以 使用useReducer, 可以看一下 下面的例子: import React, { useReducer...
  • <p>How would I go about passing a dynamic initial state into <code>useReducer</code>? Something like the following: <pre><code>javascript const useValue = value => useReducer(store.reducer,...
  • <div><p>Seems like these abstractions would be portable onto https://reactjs.org/docs/hooks-reference.html#usereducer ... what do you think?</p><p>该提问来源于开源项目:HenrikJoreteg/redux-...
  • useContext-useReducer-practice 用CodeSandbox创建
  • 使用redux devtools来检查useState和useReducer
  • react hooks中的 useReducer

    2020-10-14 17:39:21
    useReducer是React提供的一个高级Hook,它不像useEffect、useState、useRef等必须hook一样,没有它我们也可以正常完成需求的开发,但useReducer可以使我们的代码具有更好的可读性、可维护性、可预测性。 下面我们会...
  • <p>In react-hooks-async, I tried useReducer but it was too ugly, the current code with forceUpdate is pretty readable. So, I gave up. I could try further. There could be a better implementation with ...
  • React Hooks之useReducer

    千次阅读 2018-12-28 16:41:16
    useReducer :接受类型为 (state, action) =&amp;amp;amp;amp;gt; newState 的reducer,并返回与 dispatch 方法配对的当前状态。(如果你熟悉Redux,你已经知道它是如何工作的。) 下面定义两个计数器Counter...
  • const [state, dispatch] = useReducer(reducer, initialArg, init); useState的替代方案。它接收一个形如(state, action) => newState的 reducer,并返回当前的 state 以及与其配套的dispatch方法。 在某些...
  • 如何使用useReducer Hook

    2019-09-18 06:41:29
    咱们将一起讨论“reducer”实际上是什么,以及如何利用useReducer来管理组件中的复杂状态,以及这个新钩子对Redux意味着什么?Reducer 是什么鬼如果你熟悉Redux或数组上中的reduce方法,你大概就知道“reducer”是...
  • React Hooks --useReducer

    2020-11-09 15:27:38
    为了更好的理解useReducer,所以先要了解Javascript里的Reducer是什么。reducer其实就是一个函数,这个函数接受两个参数,一个是状态,一个用来控制业务逻辑的判断参数。 如下所示: function countReducer(state, ...
  • Vue useReducer 受React Hooks的useReducer启发。 安装 适用于Vue v3 以下命令将安装vue-use-reducer v2。 $ yarn add vue-use-reducer@next // or $ npm i vue-use-reducer@next 对于Vue v2 以下命令将安装vue-...
  • 要想全局使用reducer的数据状态(useContext、useReducer),必须要保证组件在包裹内,和react-redux的Provider一致 // index.js import React from 'react'; import ReactDOM from 'react-dom'; import Store from...
  • 目录前言一、useReducer1.0 useReducer的API1.1 传递object1.2 useReducer的最佳实践总结 前言 最近开始学习React,跟着Kent学,有很多干货,这里分享React Hook中的useReducer 很多时候并不需要useReducer,因为...
  • 六、useReducer的使用

    2020-08-31 15:04:58
    二、useReducer的使用 一、Reducer是什么? Reducer的兴起是从Redux广泛使用开始的,但不仅仅存在于Redux中。Reducer其实就是一个函数,这个函数接收两个参数,一个是状态(state),另一个是用来控制业务逻辑的判断...
  • useContext和useReducer是react16.8之后新出的,用这两个可以构建一个redux,下面来看下 import React,{createContext}from 'react' export default Context=createContext() //reducer函数 function reducer...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 612
精华内容 244
关键字:

usereducer