Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在ReactJS中使用上下文更改不同函数中的属性_Reactjs - Fatal编程技术网

如何在ReactJS中使用上下文更改不同函数中的属性

如何在ReactJS中使用上下文更改不同函数中的属性,reactjs,Reactjs,我是新来的。我有一个将源数据发送到函数的提供程序,名为CheckBook。在CheckBook中,我有可以显示源数据的列和行。我要做的是更改cancelled属性(为true或false)当我点击我创建的复选按钮时,我也很难解释我的问题。但我想知道如何在react中使用上下文。 这是我的源数据 const sourceData = [ { tid: 1, date: '2020-03-10T10:47:02-05:00', credit: 100, descr

我是新来的。我有一个将源数据发送到函数的提供程序,名为CheckBook。在CheckBook中,我有可以显示源数据的列和行。我要做的是更改cancelled属性(为true或false)当我点击我创建的复选按钮时,我也很难解释我的问题。但我想知道如何在react中使用上下文。 这是我的源数据

const sourceData = [
  {
    tid: 1,
    date: '2020-03-10T10:47:02-05:00',
    credit: 100,
    description: 'initial deposit',
  },
  {
    tid: 2,
    check_no: 1,
    date: '2020-03-10T16:50:59Z',
    debit: 3.14,
    description: 'gum',
    canceled: true,
  },
  {
    tid: 3,
    check_no: 2,
    date: '2020-03-10T16:49:21-05:00',
    debit: 3.14,
    description: 'gum',
  }

];

这是我的提供商

const CheckContext = React.createContext({
  entries: [],
  getEntries: async () => {},
  setCancel: async (tid, value) => {},
});

export function CheckProvider(props) {
  const [entries, setEntries] = React.useState(() =>
    sourceData.map((item, rid) => ({
      ...item,
      rid,
      date: new Date(Date.parse(item.date)),
      canceled: !!item.canceled,
    }))
  );

  const contextValue = React.useMemo(() => {
    const setCancel = async (tid, value) => {
      setEntries((currentEntries) =>
        currentEntries.map((item) => ({
          ...item,
          canceled: item.tid === tid ? value : item.canceled,
        }))
      );
    };

    return {
      entries: entries.map((item) => ({ ...item, balance: 0 })),
      setCancel,
    };
  }, [entries]);

  return (
    <CheckContext.Provider value={contextValue}>
      {props.children}
    </CheckContext.Provider>
  );
}

const [entries, setEntries] = React.useState(() =>
    sourceData.map((item, rid) => ({
      ...item,
      rid,
      date: new Date(Date.parse(item.date)),
      canceled: !!item.canceled,
      balance: 0
    }))
  );

  const setCancel = (tid, value) => {
    setEntries((currentEntries) =>
      currentEntries.map((item) => ({
        ...item,
        canceled: item.tid === tid ? value : item.canceled
      }))
    );
  };

  return (
    <CheckContext.Provider value={{ entries, setCancel }}>
      {props.children}
    </CheckContext.Provider>
  );
const CheckContext=React.createContext({
条目:[],
getEntries:async()=>{},
setCancel:async(tid,value)=>{},
});
导出函数检查提供程序(道具){
const[entries,setEntries]=React.useState(()=>
sourceData.map((项目,rid)=>({
…项目,
摆脱
日期:新日期(date.parse(item.date)),
取消:!!item.cancelled,
}))
);
const contextValue=React.useMoom(()=>{
const setCancel=async(tid,value)=>{
setEntries((currentEntries)=>
currentEntries.map((项目)=>({
…项目,
取消:item.tid==tid?值:item.cancelled,
}))
);
};
返回{
条目:entries.map((item)=>({…item,余额:0})),
设置取消,
};
},[条目];
返回(
{props.children}
);
}
我有一个名为“支票簿”的函数。它以行和列的形式显示我的sourceData属性。我创建了一个输入元素,将cancelled属性更改为truefalse。但我不知道如何使用上下文更改它

// component to render the check book
export function CheckBook(props) {
  const value=React.useContext(CheckContext)
  console.log(value)
  const [sortedField, setSortedField] = React.useState({
    sortBy: '',
  });

  const toggleSort = (key) => {
    let sortBy = 'asc';
    setSortedField({ key, sortBy });
  };

  function renderRows(state) {
    return (
      <>
        {state.entries.map((e, index) => (
          <tr>
            <th scope="row">{e.date.toUTCString()}</th>
            <th scope="row">{e.tid}</th>
            <th scope="row">{e.debit}</th>
            <th scope="row">{e.credit}</th>
            <th scope="row">{e.balance}</th>
            <th scope="row">{e.description}</th>
            <th scope="row">
              <input
                type="checkbox"
                
              ></input>
            </th>
          </tr>
        ))}
      </>
    );
  }

  return (
    <CheckContext.Consumer>
      {(state) => (
        <div className={'tableWrapper'}>
          <table>
            <thead>
              <HeaderRow sortedField={sortedField} toggleSort={toggleSort} />
            </thead>
            <tbody>{renderRows(state)}</tbody>
          </table>
        </div>
      )}
    </CheckContext.Consumer>
  );
}

```This is my output how it look like
![Screenshot_1|690x285](upload://gQ8BOM9nNpG0qMQt2E8hwUBwyuo.png)
//用于呈现支票簿的组件
导出功能支票簿(道具){
常量值=React.useContext(CheckContext)
console.log(值)
常量[sortedField,setSortedField]=React.useState({
糟糕的是:'',
});
常量切换排序=(键)=>{
设sortBy='asc';
setSortedField({key,sortBy});
};
函数renderRows(状态){
返回(
{state.entries.map((e,index)=>(
{e.date.toutString()}
{e.tid}
{e.debit}
{e.credit}
{e.balance}
{e.description}
))}
);
}
返回(
{(州)=>(
{renderRows(state)}
)}
);
}
```这是我的输出
![截图1 | 690x285](upload://gQ8BOM9nNpG0qMQt2E8hwUBwyuo.png)

您需要在支票簿组件中使用setCancel

提供商

const CheckContext = React.createContext({
  entries: [],
  getEntries: async () => {},
  setCancel: async (tid, value) => {},
});

export function CheckProvider(props) {
  const [entries, setEntries] = React.useState(() =>
    sourceData.map((item, rid) => ({
      ...item,
      rid,
      date: new Date(Date.parse(item.date)),
      canceled: !!item.canceled,
    }))
  );

  const contextValue = React.useMemo(() => {
    const setCancel = async (tid, value) => {
      setEntries((currentEntries) =>
        currentEntries.map((item) => ({
          ...item,
          canceled: item.tid === tid ? value : item.canceled,
        }))
      );
    };

    return {
      entries: entries.map((item) => ({ ...item, balance: 0 })),
      setCancel,
    };
  }, [entries]);

  return (
    <CheckContext.Provider value={contextValue}>
      {props.children}
    </CheckContext.Provider>
  );
}

const [entries, setEntries] = React.useState(() =>
    sourceData.map((item, rid) => ({
      ...item,
      rid,
      date: new Date(Date.parse(item.date)),
      canceled: !!item.canceled,
      balance: 0
    }))
  );

  const setCancel = (tid, value) => {
    setEntries((currentEntries) =>
      currentEntries.map((item) => ({
        ...item,
        canceled: item.tid === tid ? value : item.canceled
      }))
    );
  };

  return (
    <CheckContext.Provider value={{ entries, setCancel }}>
      {props.children}
    </CheckContext.Provider>
  );
const[entries,setEntries]=React.useState(()=>
sourceData.map((项目,rid)=>({
…项目,
摆脱
日期:新日期(date.parse(item.date)),
取消:!!item.cancelled,
余额:0
}))
);
常量设置取消=(tid,值)=>{
setEntries((currentEntries)=>
currentEntries.map((项目)=>({
…项目,
已取消:item.tid==tid?值:item.cancelled
}))
);
};
返回(
{props.children}
);
支票簿

const { setCancel, entries } = React.useContext(CheckContext);

  function renderRows(state) {
    return (
      <>
        {entries.map((entry, index) => (
          <tr>
            <th scope="row">{entry.date.toUTCString()}</th>
            <th scope="row">{entry.tid}</th>
            <th scope="row">{entry.debit}</th>
            <th scope="row">{entry.credit}</th>
            <th scope="row">{entry.balance}</th>
            <th scope="row">{entry.description}</th>
            <th scope="row">
              <input
                type="checkbox"
                checked={entry.canceled}
                onChange={(e) => setCancel(entry.tid, e.target.checked)}
              ></input>
            </th>
          </tr>
        ))}
      </>
    );
  }
const{setCancel,entries}=React.useContext(CheckContext);
函数renderRows(状态){
返回(
{entries.map((条目,索引)=>(
{entry.date.toutString()}
{entry.tid}
{entry.debit}
{entry.credit}
{entry.balance}
{entry.description}
setCancel(entry.tid,e.target.checked)}
>
))}
);
}

这是完整的工作代码示例-

当您遇到此错误时,条目未定义错误?好的,它正在工作。我还有一个问题。如果我想改变支票簿上的余额,我该怎么做?因为setEntries可以设置余额。