无需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:
- Replace the plain variable with React state: Instead of
let i = 0, useuseStateto create a tracked state variable for your index. React will watch this variable and trigger a re-render whenever it changes. - Update state correctly: Use the state setter function to increment the index, instead of directly modifying the variable.
- 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 variablecurrentIndexinitialized to 0, and a setter functionsetCurrentIndexto update it.- Functional update in
setCurrentIndex: UsingprevIndex => (prevIndex + 1) % array.lengthensures we always use the most recent state value, which is safer than directly usingcurrentIndex + 1(especially if the increment could be triggered multiple times quickly). - Re-render trigger: Every time
setCurrentIndexis 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
相关产品推荐
相关产品推荐

