简体   繁体   English

反应 API 上下文 - Function 不起作用

[英]React API Context - Function does not work

In my application, I am using the context API to select rows and place them in an associative array.在我的应用程序中,我使用上下文 API 到 select 行并将它们放在关联数组中。 It worked with local state but with context API it doesn't access my function in LinesContext.js.它与本地 state 一起使用,但在上下文 API 下,它无法访问我在 LinesContext.js 中的 function。

import React, {createContext, useState} from "react";

export const LinesContext = createContext();

const LinesContextProvider = props => 
{
  const [lines, setLines] = useState();

  const clickLine = (e) => 
  {
    console.log(e.target.parentNode);
    if (e.target.parentNode.className.length > 0)
    {
      e.target.parentNode.classList.remove("lineClicked");
      delete lines[e.target.parentNode.id];
      console.log(lines);         
    }
    else 
    {
      e.target.parentNode.classList.add("lineClicked");
      lines[e.target.parentNode.id] = e.target.parentNode.id;
      console.log(lines);
    } 
  }

  return (
    <LinesContext.Provider value={clickLine, lines}>
      {props.children}
    </LinesContext.Provider>
  )
}

export default LinesContextProvider;

I embed my entire app in App.js.我将整个应用程序嵌入到 App.js 中。

import './App.css';
import Connection from './Components/Connection/Connection';
import Window from './Components/Window/Window';
import CourriersListe from './Components/Courriers/Liste/CourriersListe';
import DestinatairesListe from './Components/Destinataires/Liste/DestinatairesListe';
import { Routes, Route } from 'react-router-dom';
import {BrowserRouter as Router} from 'react-router-dom';
import LinesContextProvider from './Context/LinesContext';

function App() {
  return (
    <div className="App">
      <LinesContextProvider>
        <Router>
          <Routes>
            <Route 
              path="/" element={<Window id="windowConnection" 
              title="Connexion" x="100px" y="100px" w="640px" h="480px" 
              main={<Connection destination="/courriers/liste" />} 
              status="Tout est OK." fullscreen={false}/>}
            />
            <Route path="/courriers/liste" element={<CourriersListe/>} />
            <Route path="/destinataires/liste" element={<DestinatairesListe />} />
          </Routes> 
        </Router>
      </LinesContextProvider>
    </div>
  );
}

export default App;

And I'm calling this ClickLine function in Liste.js.我在 Liste.js 中调用这个 ClickLine function。 When clicking on a td, the function is supposed to be called and select / deselect the parent element, the tr, by matting it in color or not and by adding / removing it from an associative array.单击 td 时,应该调用 function 和 select / 取消选择父元素 tr,通过将其设置为颜色或不设置颜色以及从关联数组中添加/删除它。

import React, {useContext} from 'react';
import './Liste.css';
import Button from '../Button/Button';
import {LinesContext} from '../../Context/LinesContext';

function Liste(props) 
{
    const clickLine = useContext(LinesContext);
   
    const doubleClickLine = () =>
    {
        console.log("doubleClickLine"); 
    }

    return (
        <>
            <table className='tableList'>
                <thead>
                    <tr>
                        <th colSpan={props.headers.length+1}>{props.title}</th> 
                    </tr>
                    <tr>
                        {props.headers.map((header, h) =>
                            <th key={h}>{header}</th>                   
                        )}
                        <th>actions</th>  
                    </tr>
                </thead>
                <tbody>
                    {props.records.map((record, r) =>
                        <tr key={r} id={props.table+"_"+record[0]}>
                            {props.columns.map((column, c) =>
                                <td key={c} onClick={clickLine} onDoubleClick={doubleClickLine}>{record[column]}</td>         
                            )}
                            <td>
                                {props.actions.map((action, a) =>     
                                    <Button key={a} id={`${props.table}_${action[0]}_${record[0]}`} 
                                    type={action[1]} value={action[2]} click={action[3]}/>             
                                )} 
                            </td>
                        </tr>                
                    )}
                </tbody>
                <tfoot>
                    <tr>
                        <th colSpan={props.headers.length+1}>
                            {props.buttons.map((button, b) =>
                                <Button key={b} id={button[0]} type={button[1]} value={button[2]} click={button[3]}/>              
                            )}
                        </th>
                    </tr>
                </tfoot>
            </table>
        </>
    )
}

export default Liste;

Here is the problem:这是问题所在:

<LinesContext.Provider value={clickLine, lines}>

You have two values separated with a comma in your value prop.您的value道具中有两个用逗号分隔的值。 In JavaScript, the result of the expression a, b is b .在 JavaScript 中,表达式a, b的结果是b So you are effectively settings value={lines} .所以你实际上是在设置value={lines}

It's probably this.大概就是这个了。 value prop in the case of the provider is expecting one object/value to be passed once the context is accessed.在提供者的情况下, value prop 期望在访问上下文后传递一个对象/值。

<LinesContext.Provider value={clickLine, lines}>

Since, {} is syntax.因为, {}是语法。 You need another pair of brackets to pass in an object.您需要另一对括号来传递 object。

<LinesContext.Provider value={{clickLine, lines}}>

Finally, when you call useContext(LinesContext) the return value will be whatever you passed in the value prop earlier which is { clickLine, lines } .最后,当您调用useContext(LinesContext)时,返回值将是您之前在 value 属性中传递的任何value ,即{ clickLine, lines } so adjust your code accordingly,所以相应地调整你的代码,

const { clickLine, lines } = useContext(LinesContext)

in order to access the clickLine function as well as lines state properly.为了正确访问clickLine function 以及lines state。

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

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