我正在嘗試使用由頁面上的一個組件更改的背景關系中的狀態來顯示/隱藏頁面上的組件。我的頁面上有一個檔案上傳框,當上傳有效檔案時,我想在頁面上顯示一個元素,但我似乎根本無法讓它作業。誰能看到我做錯了什么?
看起來調度正在更新狀態值(如下面的瀏覽器除錯器所示),但是狀態似乎沒有在 Dashboard.js 頁面上更新。

index.js
...
import Provider from './Helpers/Provider'
ReactDOM.render(
<BrowserRouter>
<Provider>
<App />
</Provider>
</BrowserRouter>,
document.getElementById('root')
);
儀表板.js
import { useDropzone } from 'react-dropzone';
import TileGrid from '../Components/TileGrid';
import MyDropzone from '../Components/Dropzone';
import React, { useState, useEffect } from 'react';
import { Context } from '../Helpers/Provider';
export default function Dashboard() {
const [currentTime, setCurrentTime] = useState(0);
const [state, dispatch] = useState(Context);
....
return (
<div>
<h5 class="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white mr-2">Upload a PCAP file to analyse</h5>
<p>Accepted file types: .pcap, .pcapng, .tcpdump</p>
</div>
<div class="mt-5 lg:ml-2 lg:mt-0 md:mt-0">
<MyDropzone/> // File upload component
</div>
<div>
<p>{state.pcapUploaded}</p> // Should show 'false' by default, does not show at all
{ state.pcapUploaded ? <TileGrid tiles={tiles}/> : null } // Trying to get this item to show if a file has been uploaded, and not if no file has been uploaded
</div>
);
}
Dropzone.js(嘗試在此處將狀態更改為“true”)
import { useCallback, useEffect, useContext } from 'react';
import { useDropzone } from 'react-dropzone';
import { Context } from '../Helpers/Provider';
export default function MyDropzone() {
const [state, dispatch] = useContext(Context);
function PcapUploaded() {
alert("hi");
dispatch({ // Trying to update the state in context to have a value of 'true' here
type: 'UPLOADED',
payload: true,
});
}
const onDrop = useCallback(acceptedFiles => {
// Do something with the files
// alert(acceptedFiles[0].name);
PcapUploaded();
}, [])
.....
提供者.js
import { createContext, useReducer } from "react";
import Reducer from "../Reducer";
export const Context = createContext();
const initalState = {
pcapUploaded: false,
}
export default function Provider(props) {
const [state, dispatch] = useReducer(Reducer, initalState);
return (
<Context.Provider value={[state, dispatch]}>
{props.children}
</Context.Provider>
);
}
減速器.js
export default function Reducer(state, action) {
switch(action.type) {
case 'UPLOADED':
return {
pcapUploaded: true,
};
default:
throw new Error();
}
}
我一直在關注本指南:https ://remarkablemark.org/blog/2021/03/21/managing-react-state-with-context/
謝謝
uj5u.com熱心網友回復:
在你Dashboard.js嘗試
const [state, dispatch] = useContext(Context)
代替
const [state, dispatch] = useState(Context)
uj5u.com熱心網友回復:
https://codesandbox.io/s/state-not-updating-through-context-98zlz6
請使用您的代碼的作業版本檢查我的代碼框。您的代碼中的型別出現了一些錯誤,而且您在應該使用 useContext 的地方使用了 useState。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/459414.html
標籤:javascript 反应 状态
下一篇:根據時間對陣列進行排序
