You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需State/Redux,如何强制刷新Div文本并实现数组文本切换渲染?

Fixing React Re-Render Issue Without Redux

Hey, I see exactly what's going on here! The problem is you're using a plain vanilla JavaScript variable i to track your current index. React doesn't automatically re-render components when regular variables change—only when state or props update. No need for Redux here; React's built-in useState hook is all you need to make this work.

Here's the corrected approach:

  1. Replace the plain variable with React state: Instead of let i = 0, use useState to create a tracked state variable for your index. React will watch this variable and trigger a re-render whenever it changes.
  2. Update state correctly: Use the state setter function to increment the index, instead of directly modifying the variable.
  3. Add boundary checks (optional but helpful): Prevent the index from going beyond the array length to avoid errors.

Full corrected code example:

import { useState } from 'react';

const array = [{text: '1st text'}, {text: "2nd text"}];

const DialogueReceiver = () => {
  // Initialize state for current index
  const [currentIndex, setCurrentIndex] = useState(0);

  const increment = () => {
    // Update index, loop back to 0 if we reach the end of the array
    setCurrentIndex(prevIndex => (prevIndex + 1) % array.length);
  };

  return (
    <div>
      {/* Display the current text */}
      <div>{array[currentIndex].text}</div>
      {/* Button to trigger increment */}
      <div>
        <button onClick={increment}>Next Text</button>
      </div>
    </div>
  );
};

export default DialogueReceiver;

Key changes explained:

  • useState(0): Creates a state variable currentIndex initialized to 0, and a setter function setCurrentIndex to update it.
  • Functional update in setCurrentIndex: Using prevIndex => (prevIndex + 1) % array.length ensures we always use the most recent state value, which is safer than directly using currentIndex + 1 (especially if the increment could be triggered multiple times quickly).
  • Re-render trigger: Every time setCurrentIndex is called, React detects the state change and re-renders the component, updating the displayed text automatically.

Why your original code didn't work:

When you did i++, you modified a plain variable, but React had no way of knowing this change happened. State variables are React's way of tracking changes that should trigger updates to the UI.

内容的提问来源于stack exchange,提问作者MazMat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:10:12