简体   繁体   English

React - State 不通过上下文更新

[英]React - State not updating through context

I'm trying to show/hide a component on my page using a state in a context being changed by one of the components on the page.我正在尝试在页面上的一个组件更改的上下文中使用 state 在我的页面上显示/隐藏一个组件。 I have a file upload box on my page, and when a valid file is uploaded, I want to show an element on the page, however I can't seem to get it to work at all.我的页面上有一个文件上传框,当上传有效文件时,我想在页面上显示一个元素,但我似乎根本无法让它工作。 Can anyone see what I'm doing wrong at all?任何人都可以看到我做错了什么吗?

It looks like the dispatch is updating the state value (as seen below from browser debugger), however the state does not seem to be updating on the Dashboard.js page.看起来调度正在更新 state 值(如下面的浏览器调试器所示),但是 state 似乎没有在 Dashboard.js 页面上更新。 在此处输入图像描述

index.js索引.js

...
import Provider from './Helpers/Provider'

ReactDOM.render(
  <BrowserRouter>
    <Provider>
      <App /> 
    </Provider>
  </BrowserRouter>,
  document.getElementById('root')
);

Dashboard.js仪表板.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 (Trying to change the state to 'true' here) Dropzone.js(尝试在此处将 state 更改为“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();
    }, [])
.....

Provider.js Provider.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>
    );
}

Reducer.js Reducer.js

export default function Reducer(state, action) {
    switch(action.type) {
        case 'UPLOADED':
            return {
                pcapUploaded: true,
            };
        default:
            throw new Error();
    }
}

I've been following this guide: https://remarkablemark.org/blog/2021/03/21/managing-react-state-with-context/我一直在关注本指南: https://remarkablemark.org/blog/2021/03/21/managing-react-state-with-context/

Thanks谢谢

https://codesandbox.io/s/state-not-updating-through-context-98zlz6 https://codesandbox.io/s/state-not-updating-through-context-98zlz6

Please check my codesandbox with working version of your code.请使用您的代码的工作版本检查我的代码和框。 There had been made some mistakes in types in your code, also you are using useState where useContext should be used.您的代码中的类型存在一些错误,您还在应该使用 useContext 的地方使用 useState。

In you're Dashboard.js try在你的Dashboard.js中尝试

const [state, dispatch] = useContext(Context)

Instead of代替

const [state, dispatch] = useState(Context)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM