反应useContext在延迟后给出输出

时间:2020-06-17 16:21:40

标签: javascript reactjs react-redux react-router

如果登录的用户不是Admin,我需要使用useContext的数据进行身份验证。但是,它先给出值“ undefined”,然后在延迟5秒钟后给出实际值。 但是到那时,代码就中断了,因为它不能与“ undefined”一起使用。

@ViewChild()

我需要使用异步/等待吗?因为我尝试在自定义异步功能中执行此操作,并且它引发了另一个错误,所以我们不能在非反应功能中使用useContext。

3 个答案:

答案 0 :(得分:1)

我从评论中汲取了想法,并找到了解决方法。 效果也很好:

2.2.8

我希望这对我有用。 (让我知道此安全性是否有问题)

答案 1 :(得分:0)

您可以设置一个useEffect钩子,以在state(userData)更改时执行副作用(重定向到“ /”):

替换:

if (!userData.user.isAdmin) {
  history.push("/");
}

具有:

useEffect(() => {
  if (userData && userData.user && !userData.user.isAdmin) {
    history.push("/");
  }
}, [userData]); // tell React to skip applying this effect if userData hasn't changed between re-renders. 

有关Using the Effect Hook

的更多信息

然后,您可以根据不同情况返回不同的组件:

if (!userData) return <p>Loading</p>;
if (!userData.user.isAdmin) return <p>You are not an admin. Redirecting...</p>;
return <h1>Admin Panel</h1>;

答案 2 :(得分:0)

您可能要考虑扩展Route组件,并在验证时在AuthContext上添加JTable状态(并且可能会出错)。

import java.awt.BorderLayout; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class JTableFromExcel { private JFrame frame; private JTable simpleTable; private JTable excelTable; private JScrollPane scrollForSimpleTable; private JScrollPane scrollForExcelTable; private String[] columnNames = {"Name", "Profession", "Salary"}; private String[][] data = {{"Foo", "Foo_Prof", "12345"}, {"Bar", "Bar_Prof", "13579"}}; private List<String> columnNamesFromExcel; private List<List<String>> dataFromExcel; //Creates the UI private void createAndShowGUI() { retrieveDataFromExcel(); frame = new JFrame(getClass().getSimpleName()); simpleTable = new JTable(data, columnNames); scrollForSimpleTable = new JScrollPane(simpleTable); DefaultTableModel tableModel = new DefaultTableModel(columnNamesFromExcel.toArray(), 0); for (List<String> row : dataFromExcel) { tableModel.addRow(row.toArray(new String[0])); } excelTable = new JTable(tableModel); scrollForExcelTable = new JScrollPane(excelTable); frame.add(scrollForSimpleTable, BorderLayout.WEST); frame.add(scrollForExcelTable, BorderLayout.EAST); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } //Opens the Excel file and sets up the data and column names @SuppressWarnings("resource") private void retrieveDataFromExcel() { FileInputStream excelFile; columnNamesFromExcel = new ArrayList<>(); dataFromExcel = new ArrayList<>(); try { excelFile = new FileInputStream(new File("PATH/TO/YOUR/FILE.xlsx")); Workbook workbook = new XSSFWorkbook(excelFile); Sheet datatypeSheet = workbook.getSheetAt(0); Iterator<Row> iterator = datatypeSheet.iterator(); //We use an iterator to get all rows while (iterator.hasNext()) { Row currentRow = iterator.next(); Iterator<Cell> cellIterator = currentRow.iterator(); List <String> dataRow = new ArrayList<>(); while (cellIterator.hasNext()) { Cell currentCell = cellIterator.next(); if (currentRow.getRowNum() == 0) { //Row 0 is the header if (currentCell.getCellType() == CellType.STRING) { columnNamesFromExcel.add(currentCell.getStringCellValue()); } else if (currentCell.getCellType() == CellType.NUMERIC) { columnNamesFromExcel.add(currentCell.getStringCellValue()); } } else { if (currentCell.getCellType() == CellType.STRING) { dataRow.add(currentCell.getStringCellValue()); } else if (currentCell.getCellType() == CellType.NUMERIC) { dataRow.add(String.valueOf(currentCell.getNumericCellValue())); } } System.out.print(currentCell + " "); } if (currentRow.getRowNum() > 0) { //Row 0 is the header, if we add the first row, it will add an empty array because we didn't add anything to it before, so we skip it dataFromExcel.add(dataRow); } System.out.println(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { SwingUtilities.invokeLater(new JTableFromExcel()::createAndShowGUI); } }

NAME PROFESSION SALARY 
FOO FOO_PROF 12345.0 
BAR BAR_PROF 13579.0 
WAKANDA WAKANDA_PROF 99999.0 

您可以按以下方式使用此组件:

loading

更新:react-router网站上有一个非常有用的示例,带有此工作流程 https://reacttraining.com/react-router/web/example/auth-workflow