简体   繁体   English

ReactJS - 在箭头 function 中设置 state

[英]ReactJS - setting state in an arrow function

I'm trying to figure out how to set the initial state in my React app inside an arrow function.我试图弄清楚如何在我的 React 应用程序中的箭头 function 中设置初始 state。 I've found the example here: https://reactjs.org/docs/hooks-state.html but it's not helping me a lot.我在这里找到了这个例子: https://reactjs.org/docs/hooks-state.html但这对我没有多大帮助。 I want to put tempOrders and cols into the state so my other components have access to them and can change them.我想将tempOrderscols放入 state 以便我的其他组件可以访问它们并可以更改它们。

Here is my code:这是我的代码:

// creating tempOrders array and cols array above this
const App = () => {
const [orders, setOrders] = useState(tempOrders);
const [columns, setColumns] = useState(cols);

return (
    <div className={'App'}>
        <Schedule
          orders={orders}
          setOrders={setOrders}
          columns={columns}
          setColumns={setColumns}
        />
    </div>
   );
 };

 export default App;

Now my other related question is if I don't pass in those 4 variables/functions into Schedule , ESLint complains to me about them being unused variables in the 2 const lines above.现在我的另一个相关问题是,如果我不将这 4 个变量/函数传递给Schedule ,ESLint 会向我抱怨它们是上面 2 个const行中未使用的变量。 I wouldn't think I would need to pass them in because that is the whole point of state, you just have access to them without needing to pass them around.我认为我不需要传递它们,因为这就是 state 的全部意义所在,您只需访问它们而无需传递它们。

You should always keep the state at the top-level component where it needs to be accessed.您应该始终将 state 保留在需要访问的顶级组件中。 In this case you should define the state in the Schedule -Component since it's not used anywhere else.在这种情况下,您应该在Schedule -Component 中定义 state,因为它没有在其他任何地方使用。

If you have a more complex hierachy of components and want to create a shared state (or make a state globally accessible) I would suggest following thump rule:如果您有更复杂的组件层次结构并想要创建共享 state (或使 state 全局可访问)我建议遵循 thump 规则:

  1. For small to medium sized apps use the context -API with the useContext -hook ( https://reactjs.org/docs/hooks-reference.html#usecontext ).对于中小型应用程序,使用context -API 和useContext -hook ( https://reactjs.org/docs/hooks-reference.html#usecontext )。 It's fairly enough for most cases.对于大多数情况来说,这已经足够了。
  2. For large apps use redux .对于大型应用程序,请使用redux Redux needs a lot of boilerplate and adds complexity to your app (especially with typescript), which is often not required for smaller apps. Redux 需要大量样板文件并增加应用程序的复杂性(尤其是使用打字稿),而小型应用程序通常不需要。 Keep in mind that redux is not a replacement for the context -API.请记住,redux 不能替代context -API。 They work well in conjunction and can/should be used together.它们可以很好地结合使用,并且可以/应该一起使用。

EDIT编辑

Simple example for useContext : useContext的简单示例:

ScheduleContext.js ScheduleContext.js

import React from "react";

export const ScheduleContext = React.createContext();

App.jsx应用程序.jsx

import {ScheduleContext} from "./ScheduleContext";

const App = () => {
const [orders, setOrders] = useState(tempOrders);
const [columns, setColumns] = useState(cols);

const contextValue = {orders, setOrders, columsn, setColumns};

return (
    <div className={'App'}>
      <ScheduleContext.Provider value={contextValue}>
        <Schedule/>
      </ScheduleContext.Provider>
    </div>
   );
 };

 export default App;

You can now use the context in any component which is a child of the <ScheduleContext.Provider> .您现在可以在作为<ScheduleContext.Provider>的子组件的任何组件中使用上下文。

Schedule.jsx时间表.jsx

import React, {useContext} from "react";
import {ScheduleContext} from "./ScheduleContext";

const Schedule = () => {
const {orders, setOrders, columsn, setColumns} = useContext(ScheduleContext);

// now you can use it like
console.log(orders)

return (...) 
}

Note that you could als provide the context inside the <Schedule> -component instead of <App> .请注意,您也可以在<Schedule> -component 而不是<App>中提供上下文。 I wrote this from my head, but it should work.我从头上写了这个,但它应该工作。 At least you should get the idea.至少你应该明白这一点。

it seems you want the child component "Schedule" have to change the father's state...... is correct?看来您希望子组件“Schedule”必须更改父亲的state……对吗?

so you can try to write like this example:所以你可以试着像这个例子那样写:

import React, {useState} from 'react';
import './App.css';

function Test(props){
    const{setCount,count}=props    
    return(
        <div>
        <h1>hello</h1>
        <button onClick={() => setCount(count + 1)}>
                Click me
        </button>
        </div>
    )
}


function App() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);
  return (
    <div>


      <Test
        setCount={setCount}
        count={count}
      />
      {count}
    </div>
  );
}
export default App;

https://repl.it/@matteo1976/ImperfectYawningQuotes https://repl.it/@matteo1976/ImperfectYawningQuotes

Where my Test would work as your Schedule我的测试在哪里可以作为你的日程安排

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

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