【问题标题】:How to pass states to components in React without each passed state being same reference如何在 React 中将状态传递给组件,而每个传递的状态都不是相同的引用
【发布时间】:2020-09-18 05:14:35
【问题描述】:

我正在尝试通过点击计数器将状态传递给几个组件。所以我可以点击一个计数器来增加计数状态的值,如果我停在 10 并将其发送到一个组件,我希望下次我使用计数器并将它设置为 15,我需要它将其发送到另一个组件(或同一个组件),但现在计数状态为 15。我不想将状态的两个实例都设置为 15。每个状态都应该保留它们的数字。

JSX

<div className="addnum" onClick={() => addUnits()}>+</div>

JS

const [units,setUnits] = useState(0)
function addUnits() {
    setUnits(prev => prev+1)
} 

一些组件 1

<div>{units}</div>

一些组件 2

<div>{units}</div> 

我的问题是当我设置一个状态时,另一个接收到相同的状态,这是正常的。如何删除引用或创建每个状态的副本,以便它们是独立的?

我看到这篇文章回答了使用基于类的组件时的问题,但我的状态不是数组,所以我怎么能在这里做同样的事情? https://stackdev.io/question/434/copy-the-state-in-react-without-reference

【问题讨论】:

  • 在每个组件中都可以保存在值中
  • 什么?你能解释一下你的意思吗?理想情况下有一个例子

标签: javascript reactjs use-state


【解决方案1】:

据我了解。您有计数器列表和所谓的一些组件列表。 所以这种情况下直接的数据结构是数组。 此外,需要计时器在一些停机时间后创建新插槽。 useReducer 是处理非标量状态的更好方法。 类似于以下内容:

const initialState = [0];

function reducer(state, action) {
  const [head, ...tail] = state;
  switch (action.type) {
    case 'inc':
      return [head + 1, ...tail];
    case 'new':
      return [0, ...state];
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  const timer = useRef(null);
  const inc = useCallback(() => {
    if (timer.current) clearTimeout(timer.current);
    timer.current = setTimeout(() => dispatch({type: 'new'}), 1000);
    dispatch({type: 'inc'});
  }, [timer, dispatch]);
  useEffect(() => () => {
    if (timer.current) clearTimeout(timer.current);
  });
  return (
    <>
      {state.map((count, i) => <div key={i}>{count}</div>)}
      <button onClick={inc}>+</button>
    </>
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-04
    • 2019-01-20
    • 2022-01-18
    • 1970-01-01
    • 2018-01-15
    • 2017-01-26
    • 2017-11-07
    • 2016-12-05
    相关资源
    最近更新 更多