在react函数组件中的const函数中,react redux状态不更新



为了给出最短的背景故事,我需要一个全局状态,所以我第一次使用redux。

我想做的是在一个需要redux信息的组件中每隔200毫秒左右运行一个函数,并更改组件的状态,这通常会导致重新渲染。

目前,我的函数将运行,但它不会从redux中获得新信息,值只是显示为原始值。

我的问题有三个:我处理这个问题正确吗?为什么我的组件一直在重新渲染?最重要的是,为什么redux没有给我正确的值?

我尝试了以下步骤进行调试,但都不起作用:

  • 我最初认为我没有正确调度,或者我的redux状态没有正确更改。为了测试这一点,我在redux reducer中打印出了状态值,显示该值正在更改
  • 然后我认为我一定是弄错了数据,所以我在react函数组件内初始化数据后立即记录了数据的值,这给了我正确的值,并提醒我组件一直在重新渲染
  • 最后,我认为这个问题与我使用useEffect来确保它只运行一次有关,当我将setInterval置于useEffect之外时,它确实具有正确的值,不幸的是,该函数一直在反复启动,直到它开始崩溃应用程序

因此,这里有一些代码应该让你了解这个问题(文件已经被截断和抽象,以保持代码的重点,但当以这种方式使用时,问题无论如何都会出现):

Store.js

import { configureStore } from '@reduxjs/toolkit'
import mySlice from '../features/slice/mySlice'
export default configureStore({
reducer: {
slice: mySlice, 
},
})

下一个mySlice.js

import { createSlice, current } from '@reduxjs/toolkit'
export const mySlice = createSlice({
name: 'slice',
initialState: {
currentWord: 0,
},
reducers: {
incrementWord: (state) => {
console.log(state.currentWord)
state.currentWord += 1
}
},
})
export const { incrementWord } = mySlice.actions
export default mySlice.reducer

接下来是组件(有条件地渲染)MyComponent.js


import React, {useEffect } from 'react';
import { Text} from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import {incrementWord} from '../../features/slice/mySlice';

const MyComponent = () => { // naturally there is more to this function but I think this makes it simpler
const dispatch = useDispatch();
const sentences = () => {return //gets data based on redux}
const currentWord = useSelector((state) => state.game.currentWord);

const tickSentence = ()=>{ // HERE IS WHERE I CANT GET THE DATA
dispatch(incrementWord());
console.log(currentWord) // Always returns 0
}
useEffect(()=>{
setInterval(()=>{tickSentence()}, 1000);
},[])
console.log(currentWord) // returns actual value
// setInterval(()=>{tickSentence()},1000); // If I use this the function works but it keeps making new intervals leading to infinite calls
return (
<Text>{sentences[currentWord]}</Text> // NOT ACTUAL USAGE 
)
}
export default MyComponent;

当保持运行时,React Native Debugger中的日志监视器显示状态:{}1密钥切片:{}多个键currentWord:581提前非常感谢你们,我很高兴发布任何信息并尝试任何配置,因为我已经花了很多时间在这方面了。

编辑:错误地复制了商店代码。

已编辑

为了防止多次调用interval->清除组件卸载时的间隔

useEffect(() => {
const yourInterval = setInterval(() => {
console.log('This will run every second');
}, 1000);
return () => clearInterval(yourInterval); // This will clear the interval when component unmounts
}, []);

此处的幻灯片初始化错误

import { configureStore } from '@reduxjs/toolkit'
import slice from '../features/slice/mySlice'
export default configureStore({
reducer: {
slice: mySlice, // mySlice is undefined, you should pass slice instead
},
})

解决方案

若要在函数中获取currentWord的值,可以在currentWord上创建一个useEffect,并用currentWord作为参数调用函数。

const yourFunction = (word) => console.log(word)
useEffect(() => {
yourFunction(currentWord)
}, [currentWord]);

最新更新