加载此组件时,fetch函数应提取数据,并使用reducer将数据存储在存储区中。当我使用useSelector选择该数据并使用useState初始化该值时,它不会在第一次渲染中更新。我希望使用useState来获取和存储数据。请帮助我使用useState将提取的数据存储在状态变量中,以便在第一次渲染时初始化提取的数据。
import { useDispatch, useSelector } from 'react-redux';
import { fetchQA } from '../../store/actions/qp';
import ListQA from '../../components/ListQA';
const QAScreen = props =>{
subjectId = props.route.params.subjectId;
const dispatch = useDispatch()
// fetching the data using dispatch
useEffect(()=>{
dispatch(fetchQA(subjectId))
},[dispatch]);
const selectedQuestions = useSelector(state => state.qa.questionAndAnswers);
**const [userTestDetails,setUserTestDetails] = useState(selectedQuestions);**
return(<View>
<Text> welcome to QA Screen</Text>
<FlatList **data={userTestDetails}** // not updating on initial render
keyExtractor={item=>item.questionId}
renderItem={itemData => <ListQA data={itemData.item} index={itemData.index} />}
/>
</View>
)
}
您不需要将从redux获得的数据存储到状态中,您可以直接使用该值,除非您想进行一些本地操作
const QAScreen = props =>{
subjectId = props.route.params.subjectId;
const dispatch = useDispatch()
// fetching the data using dispatch
useEffect(()=>{
dispatch(fetchQA(subjectId))
},[dispatch]);
const userTestDetails = useSelector(state => state.qa.questionAndAnswers);
return(<View>
<Text> welcome to QA Screen</Text>
<FlatList data={userTestDetails}
keyExtractor={item=>item.questionId}
renderItem={itemData => <ListQA data={itemData.item} index={itemData.index} />}
/>
</View>
)
}
此外,由于您正在调度一个获取和更新reducer中数据的操作,因此您不会立即获得数据是正确的,如果您希望更新状态,则需要使用useEffect
const QAScreen = props =>{
subjectId = props.route.params.subjectId;
const dispatch = useDispatch()
// fetching the data using dispatch
useEffect(()=>{
dispatch(fetchQA(subjectId))
},[dispatch]);
const selectedQuestions = useSelector(state => state.qa.questionAndAnswers);
const [userTestDetails,setUserTestDetails] = useState(selectedQuestions);
useEffect(() => {
setUserTestDetails(userTestDetails);
}, [selectedQuestions]);
...
}