等待反应上下文后组件不重新渲染
Posted
技术标签:
【中文标题】等待反应上下文后组件不重新渲染【英文标题】:Component not re-rendering after waiting for react context 【发布时间】:2021-01-29 01:43:33 【问题描述】:我正在检查 isFetchingData 是否还没有渲染,但是一旦 isFetchingData 设置为 false,它就不会重新渲染。我在上下文中有 useEffect,我希望一旦将 isFetchingData 设置为 false,它会重新渲染。有什么想法吗?
当我刷新页面时,它会使用数据呈现。所以我认为它与重新渲染有关。
我正在使用反应上下文来获取数据并公开函数来过滤该数据并得到我需要的东西。
上下文:
import React, useEffect, useState from 'react';
import getAllEmployees from 'my-services/employee/getAllEmployees';
import arrayOf, node, oneOfType from 'prop-types';
export const EmployeeContext = React.createContext(
allEmployees: [],
getActiveEmployees: () => [],
getTerminatedEmployees: () => []
);
const EmployeesProvider = ( children ) =>
const [isFetchingData, setIsFetchingData] = useState(true);
const [allEmployees, setAllEmployees] = useState();
useEffect(() =>
getAllEmployees().then(
//doing something
).then(employees =>
setAllEmployees(employees);
setIsFetchingData(false);
);
, [isFetchingData])
const context =
isFetchingData,
allEmployees,
getActiveEmployees: () =>
allEmployees.filter(x => x.status === 'Current'),
getTerminatedEmployees: () =>
allEmployees.filter(x => x.status === 'Terminated')
;
return (
<EmployeeContext.Provider value=context>children</EmployeeContext.Provider>
);
;
EmployeesProvider.propTypes =
children: oneOfType([node, arrayOf(node)])
;
EmployeesProvider.defaultProps =
children: undefined
;
export default EmployeesProvider;
组件:
import React, useContext from 'react';
import styled from 'styled-components';
import EmployeeContext from 'my-contexts/EmployeeContext';
import EmployeeCard from '../../../components/EmployeeCard';
const EmployeesTab = () =>
const
getActiveEmployees,
getTerminatedEmployees,
isFetchingData
= useContext(EmployeeContext);
let activeEmployees = [];
let terminatedEmployees = [];
if (!isFetchingData)
activeEmployees = getActiveEmployees();
terminatedEmployees = getTerminatedEmployees();
if(isFetchingData)
return <p>Loading</p>;
return (
<Outer>
<TopHeader>
<H3>Employees (activeEmployees.length)</H3>
</TopHeader>
<Wrapper>
activeEmployees.map(employee =>
return (
<EmployeeCard
id=employee.id
guid=employee.guid
firstName=employee.name.first
lastName=employee.name.last
jobTitle=employee.jobTitle
/>
);
)
</Wrapper>
<H3>Terminated employees(terminatedEmployees.length)</H3>
<Wrapper>
terminatedEmployees.map(employee =>
return (
<EmployeeCard
id=employee.id
guid=employee.guid
firstName=employee.name.first
lastName=employee.name.last
jobTitle=employee.jobTitle
/>
);
)
</Wrapper>
</Outer>
);
;
export default EmployeesTab;
【问题讨论】:
【参考方案1】:我认为可能存在很多问题。 首先,请检查整个组件是否被上下文提供者关闭。 例如
<EmployeesProvider>
<EmployeesTab/>
<EmployeesProvider/>
请检查这个问题。
【讨论】:
以上是关于等待反应上下文后组件不重新渲染的主要内容,如果未能解决你的问题,请参考以下文章