最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to access the latest state value in the functional component in React - Stack Overflow

programmeradmin2浏览0评论
import React, { useState } from "react";
import Child from "./Child";
import "./styles.css";

export default function App() {
  let [state, setState] = useState({
    value: ""
  });

  let handleChange = input => {
    setState(prevValue => {
      return { value: input };
    });
    console.log(state.value);
  };
  return (
    <div className="App">
      <h1>{state.value}</h1>

      <Child handleChange={handleChange} value={state.value} />
    </div>
  );
}
import React from "react";

function Child(props) {
  return (
    <input
      type="text"
      placeholder="type..."
      onChange={e => {
        let newValue = e.target.value;
        props.handleChange(newValue);
      }}
      value={props.value}
    />
  );
}

export default Child;

Here I am passing the data from the input field to the parent component. However, while displaying it on the page with the h1 tag, I am able to see the latest state. But while using console.log() the output is the previous state. How do I solve this in the functional React component?

import React, { useState } from "react";
import Child from "./Child";
import "./styles.css";

export default function App() {
  let [state, setState] = useState({
    value: ""
  });

  let handleChange = input => {
    setState(prevValue => {
      return { value: input };
    });
    console.log(state.value);
  };
  return (
    <div className="App">
      <h1>{state.value}</h1>

      <Child handleChange={handleChange} value={state.value} />
    </div>
  );
}
import React from "react";

function Child(props) {
  return (
    <input
      type="text"
      placeholder="type..."
      onChange={e => {
        let newValue = e.target.value;
        props.handleChange(newValue);
      }}
      value={props.value}
    />
  );
}

export default Child;

Here I am passing the data from the input field to the parent component. However, while displaying it on the page with the h1 tag, I am able to see the latest state. But while using console.log() the output is the previous state. How do I solve this in the functional React component?

Share Improve this question edited May 22, 2020 at 9:03 Drew Reese 203k17 gold badges235 silver badges267 bronze badges asked May 22, 2020 at 8:55 harsha rayharsha ray 2331 gold badge3 silver badges12 bronze badges 8
  • console.log(), will always give you the previousState , since state change is async process. You can use useEffect() react hook to check the current state. – Harmandeep Singh Kalsi Commented May 22, 2020 at 8:58
  • Non-functional React uses componentDidUpdate; with functional React you have to use the useEffect hook with a dependency array containing the state variable. However, what exactly are you trying to achieve? You are composing the latest value right before the console.log() command, so you have full access to it right then and there. What's the goal here? – user5734311 Commented May 22, 2020 at 8:58
  • Check this for your reference : stackoverflow.com/questions/31702861/… – Harmandeep Singh Kalsi Commented May 22, 2020 at 8:59
  • @ChrisG I am just trying to have the same output at both places, in the console log and while displaying it on the page with h1 – harsha ray Commented May 22, 2020 at 9:00
  • But why? A console.log() has no function for the user. Anyway, just use newState = { value: input };, then use newState to update the state and log it. – user5734311 Commented May 22, 2020 at 9:06
 |  Show 3 more comments

3 Answers 3

Reset to default 9

React state updates are asynchronous, i.e. queued up for the next render, so the log is displaying the state value from the current render cycle. You can use an effect to log the value when it updates. This way you log the same state.value as is being rendered, in the same render cycle.

export default function App() {
  const [state, setState] = useState({
    value: ""
  });

  useEffect(() => {
    console.log(state.value);
  }, [state.value]);

  let handleChange = input => {
    setState(prevValue => {
      return { value: input };
    });
  };

  return (
    <div className="App">
      <h1>{state.value}</h1>

      <Child handleChange={handleChange} value={state.value} />
    </div>
  );
}

Two solution for you: - use input value in the handleChange function

let handleChange = input => {
   setState(prevValue => {
     return { value: input };
   });
   console.log(state.value);
 };
  • use a useEffect on the state

    useEffect(()=>{ console.log(state.value) },[state])

Maybe it is helpful for others I found this way...

I want all updated projects in my state as soon as I added them so that I use use effect hook like this.

useEffect(() => {
    [temp_variable] = projects //projects get from useSelector
    let newFormValues = {...data}; //data from useState
    newFormValues.Projects = pro; //update my data object
    setData(newFormValues); //set data using useState
},[projects]) 
发布评论

评论列表(0)

  1. 暂无评论