useState设置方法不能立即反映更改

2020/10/18 12:01 · javascript ·  · 0评论

我正在尝试学习钩子,该useState方法使我感到困惑。我正在将初始值分配给数组形式的状态。useState即使使用spread(...)或,in中的set方法对我也不起作用without spread operator我已经在另一台PC上创建了一个API,该API正在调用并获取要设置为状态的数据。

这是我的代码:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

const StateSelector = () => {
  const initialValue = [
    {
      category: "",
      photo: "",
      description: "",
      id: 0,
      name: "",
      rating: 0
    }
  ];

  const [movies, setMovies] = useState(initialValue);

  useEffect(() => {
    (async function() {
      try {
        //const response = await fetch(
        //`http://192.168.1.164:5000/movies/display`
        //);
        //const json = await response.json();
        //const result = json.data.result;
        const result = [
          {
            category: "cat1",
            description: "desc1",
            id: "1546514491119",
            name: "randomname2",
            photo: null,
            rating: "3"
          },
          {
            category: "cat2",
            description: "desc1",
            id: "1546837819818",
            name: "randomname1",
            rating: "5"
          }
        ];
        console.log(result);
        setMovies(result);
        console.log(movies);
      } catch (e) {
        console.error(e);
      }
    })();
  }, []);

  return <p>hello</p>;
};

const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);

setMovies(result)以及setMovies(...result)不工作。可以在这里使用一些帮助。

我希望将结果变量推入movies数组中。

就像通过扩展React.Component创建的Class组件中的setState一样React.PureComponent,使用useStatehook提供的更新程序进行的状态更新也是异步的,不会立即反映出来。

同样,这里的主要问题不仅是异步性质,还在于功能基于状态的当前闭包使用状态值的事实,状态更新将反映在下一个重新渲染中,现有闭包不会受到影响,而是新的一个被创建现在,在当前状态下,挂钩中的值是通过现有的闭包获得的,并且当重新渲染时,将根据是否再次创建函数来更新闭包。

即使您添加了一个setTimeout函数,尽管超时将在发生重新渲染的时间后运行,但该函数setTimeout仍将使用其前一次关闭而不是更新后的值。

setMovies(result);
console.log(movies) // movies here will not be updated

如果要对状态更新执行操作,则需要使用useEffect钩子,就像componentDidUpdate在类组件中使用一样,因为useState返回的setter没有回调模式

useEffect(() => {
    // action on update of movies
}, [movies]);

就更新状态的语法而言,setMovies(result)状态中的先前movies替换为异步请求中可用的值。

但是,如果要将响应与先前存在的值合并,则必须使用状态更新的回调语法以及正确使用的扩展语法,例如

setMovies(prevMovies => ([...prevMovies, ...result]));

上一个答案的其他详细信息

尽管ReactsetState 异步的(类和钩子),并且很想用该事实来解释观察到的行为,但这并不是它发生原因

TLDR:原因是围绕不可变闭包范围const


解决方案:

  • 读取render函数中的值(不在嵌套函数中):

    useEffect(() => { setMovies(result) }, [])
    console.log(movies)
    
  • 将变量添加到依赖项中(并使用react-hooks / exhaustive-deps eslint规则):

    useEffect(() => { setMovies(result) }, [])
    useEffect(() => { console.log(movies) }, [movies])
    
  • 使用可变引用(无法执行上述操作时):

    const moviesRef = useRef(initialValue)
    useEffect(() => {
      moviesRef.current = result
      console.log(moviesRef.current)
    }, [])
    

解释为什么会发生:

如果异步是唯一原因,则有可能await setState()

Howerver,既propsstate假定为不改变在1渲染

对待this.state就好像它是不可变的。

对于钩子,可以通过关键字中使用常量值来增强此假设const

const [state, setState] = useState('initial')

该值在2个渲染器之间可能有所不同,但在渲染器内部和任何闭包内部(在渲染完成后寿命更长的函数,例如useEffect,任何Promise或setTimeout内部的事件处理程序)都将保持不变

考虑以下伪造但同步的类似React的实现:

// sync implementation:

let internalState
let renderAgain

const setState = (updateFn) => {
  internalState = updateFn(internalState)
  renderAgain()
}

const useState = (defaultState) => {
  if (!internalState) {
    internalState = defaultState
  }
  return [internalState, setState]
}

const render = (component, node) => {
  const {html, handleClick} = component()
  node.innerHTML = html
  renderAgain = () => render(component, node)
  return handleClick
}

// test:

const MyComponent = () => {
  const [x, setX] = useState(1)
  console.log('in render:', x) // ✅
  
  const handleClick = () => {
    setX(current => current + 1)
    console.log('in handler/effect/Promise/setTimeout:', x) // ❌ NOT updated
  }
  
  return {
    html: `<button>${x}</button>`,
    handleClick
  }
}

const triggerClick = render(MyComponent, document.getElementById('root'))
triggerClick()
triggerClick()
triggerClick()
<div id="root"></div>

在@kentcdobs文章(参见下面的参考文献)之后,我刚刚完成了useReducer的重写,这确实给了我一个可靠的结果,这些问题一点儿也没有。

参见:https : //kentcdodds.com/blog/how-to-use-react-context-effectively

我将他的可读样板浓缩为我偏爱的DRYness级别-阅读他的沙箱实现将向您展示其实际工作方式。

享受,我知道我是!

import React from 'react'

// ref: https://kentcdodds.com/blog/how-to-use-react-context-effectively

const ApplicationDispatch = React.createContext()
const ApplicationContext = React.createContext()

function stateReducer(state, action) {
  if (state.hasOwnProperty(action.type)) {
    return { ...state, [action.type]: state[action.type] = action.newValue };
  }
  throw new Error(`Unhandled action type: ${action.type}`);
}

const initialState = {
  keyCode: '',
  testCode: '',
  testMode: false,
  phoneNumber: '',
  resultCode: null,
  mobileInfo: '',
  configName: '',
  appConfig: {},
};

function DispatchProvider({ children }) {
  const [state, dispatch] = React.useReducer(stateReducer, initialState);
  return (
    <ApplicationDispatch.Provider value={dispatch}>
      <ApplicationContext.Provider value={state}>
        {children}
      </ApplicationContext.Provider>
    </ApplicationDispatch.Provider>
  )
}

function useDispatchable(stateName) {
  const context = React.useContext(ApplicationContext);
  const dispatch = React.useContext(ApplicationDispatch);
  return [context[stateName], newValue => dispatch({ type: stateName, newValue })];
}

function useKeyCode() { return useDispatchable('keyCode'); }
function useTestCode() { return useDispatchable('testCode'); }
function useTestMode() { return useDispatchable('testMode'); }
function usePhoneNumber() { return useDispatchable('phoneNumber'); }
function useResultCode() { return useDispatchable('resultCode'); }
function useMobileInfo() { return useDispatchable('mobileInfo'); }
function useConfigName() { return useDispatchable('configName'); }
function useAppConfig() { return useDispatchable('appConfig'); }

export {
  DispatchProvider,
  useKeyCode,
  useTestCode,
  useTestMode,
  usePhoneNumber,
  useResultCode,
  useMobileInfo,
  useConfigName,
  useAppConfig,
}

用法与此类似:

import { useHistory } from "react-router-dom";

// https://react-bootstrap.github.io/components/alerts
import { Container, Row } from 'react-bootstrap';

import { useAppConfig, useKeyCode, usePhoneNumber } from '../../ApplicationDispatchProvider';

import { ControlSet } from '../../components/control-set';
import { keypadClass } from '../../utils/style-utils';
import { MaskedEntry } from '../../components/masked-entry';
import { Messaging } from '../../components/messaging';
import { SimpleKeypad, HandleKeyPress, ALT_ID } from '../../components/simple-keypad';

export const AltIdPage = () => {
  const history = useHistory();
  const [keyCode, setKeyCode] = useKeyCode();
  const [phoneNumber, setPhoneNumber] = usePhoneNumber();
  const [appConfig, setAppConfig] = useAppConfig();

  const keyPressed = btn => {
    const maxLen = appConfig.phoneNumberEntry.entryLen;
    const newValue = HandleKeyPress(btn, phoneNumber).slice(0, maxLen);
    setPhoneNumber(newValue);
  }

  const doSubmit = () => {
    history.push('s');
  }

  const disableBtns = phoneNumber.length < appConfig.phoneNumberEntry.entryLen;

  return (
    <Container fluid className="text-center">
      <Row>
        <Messaging {...{ msgColors: appConfig.pageColors, msgLines: appConfig.entryMsgs.altIdMsgs }} />
      </Row>
      <Row>
        <MaskedEntry {...{ ...appConfig.phoneNumberEntry, entryColors: appConfig.pageColors, entryLine: phoneNumber }} />
      </Row>
      <Row>
        <SimpleKeypad {...{ keyboardName: ALT_ID, themeName: appConfig.keyTheme, keyPressed, styleClass: keypadClass }} />
      </Row>
      <Row>
        <ControlSet {...{ btnColors: appConfig.buttonColors, disabled: disableBtns, btns: [{ text: 'Submit', click: doSubmit }] }} />
      </Row>
    </Container>
  );
};

AltIdPage.propTypes = {};

现在,所有页面上的所有内容都可以顺利进行

真好!

谢谢肯特!

useEffect具有自己的状态/生命周期,直到您在参数中传递函数或销毁效果后,它才会更新。

对象和数组的散布或休息在useEffect内不起作用。

React.useEffect(() => {
    console.log("effect");
    (async () => {
        try {
            let result = await fetch("/query/countries");
            const res = await result.json();
            let result1 = await fetch("/query/projects");
            const res1 = await result1.json();
            let result11 = await fetch("/query/regions");
            const res11 = await result11.json();
            setData({
                countries: res,
                projects: res1,
                regions: res11
            });
        } catch {}
    })(data)
}, [setData])
# or use this
useEffect(() => {
    (async () => {
        try {
            await Promise.all([
                fetch("/query/countries").then((response) => response.json()),
                fetch("/query/projects").then((response) => response.json()),
                fetch("/query/regions").then((response) => response.json())
            ]).then(([country, project, region]) => {
                // console.log(country, project, region);
                setData({
                    countries: country,
                    projects: project,
                    regions: region
                });
            })
        } catch {
            console.log("data fetch error")
        }
    })()
}, [setData]);
// replace
return <p>hello</p>;
// with
return <p>{JSON.stringify(movies)}</p>;

现在您应该看到,您的代码确实起作用了。什么是行不通的console.log(movies)这是因为movies指向旧状态如果将移到console.log(movies)之外useEffect,就在退货单的上方,您将看到更新的电影对象。

本文地址:http://javascript.askforanswer.com/usestateshezhifangfabunenglijifanyinggenggai.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!