【发布时间】:2020-05-05 10:00:38
【问题描述】:
当这个组件被加载时, fetch 函数应该获取数据并使用 reducer 将数据存储在 store 中。当我使用 useSelector 选择该数据并使用 useState 初始化该值时,它不会在第一次渲染中得到更新。我希望使用 useState 获取和存储数据。请帮助我在 state 变量中使用 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>
)
}
【问题讨论】:
-
我不明白您为什么将
selectedQuestions放在当地状态。你是否在selectedQuestions中获得价值?
标签: reactjs react-native react-redux react-hooks