簡體   English   中英

無法有條件地渲染組件

[英]Unable to render a component conditionally

我正在嘗試根據父級的 state 有條件地渲染組件。 但我無法做到這一點。

在我當前的代碼中,我可以在“todos.length>0”之后看到組件,但是當我開始輸入任何文本字段時。

我的父組件:

function App() {
  const [title,setTitle] = React.useState("")
  const [desc, setDesc] = React.useState("")
  const [todos, setTodos] = React.useState([])

  const titleChange = (e) => {
           const value=e.target.value;
           setTitle(value)
  }

  const descChange = (e) => {
           const value=e.target.value;
           setDesc(value)
  }

  const handleCancel = () => {
    setTitle("");
    setDesc("")
  }

  const handleAdd = () => {
    const newTodos = todos;
    newTodos.push({
      title:title,
      description: desc
    });
    setTodos(newTodos)
  }

  return (
    <div >
      <label>Enter Title</label>
      <TextField onChange={(e) => titleChange(e)} value={title} />
      <label>Description</label>
      <TextArea onChange={(e) => descChange(e)} value = {desc}/>
      <Button onClick={handleCancel}>Cancel</Button>
      <Button onClick={handleAdd}>ADD</Button>
<div>
      {todos.length && <TodoList todos={todos} />}
      </div>
    </div>
  );
}

我的子組件:

export default function TodoList (props){

    React.useEffect(() => {
      console.log("mounted")
    })

    return (
        <div>
        {console.log(props)}
        </div>
    )
}

甚至,我嘗試過像這樣使用三元運算符,

todos.length ? <TodoList todos={todos} /> : null

如果其中有一些任務,我認為您想顯示待辦事項列表

todos.length > 0 ? <TodoList todos={todos} /> : null

或者你可以這樣做

{ todos.lenght > 0 && <TodoList todos={todos} /> }

{ true && expression }返回expression { false && expression }返回false

好的,您遺漏了一些東西,在您的 handleAdd function 中,您只是推送到同一個數組,這樣 React 將具有與前一個數組相同的引用,因此它將擺脫 state 更新,您應該從現有的數組創建一個新數組一 更改您的句柄添加為這樣

const handleAdd = () => {
const newTodos = [ ...todos];
newTodos.push({
  title:title,
  description: desc
});
setTodos(newTodos)

}

這樣 React 將更新 todos state,並更改

{todos.length && <TodoList todos={todos} />}

{todos.length > 0 && <TodoList todos={todos} />}

子組件中的另一件事,而不是記錄,獲取 div 中數組的大小

<div>
    {props.todos.length}
</div>

希望能幫助到你

不要突變 state。

只需更正您的手柄添加handleAdd

  const handleAdd = () => {
    setTodos([...todos, {title: title, description: desc }])
  };

希望有幫助!!!

component第一次渲染時, todos length將始終0 所以{todos.length &&條件變為false

你應該使用類似的東西來避免這個問題:

{todos.length >0  && <TodoList todos={todos} />}  

我認為您的 handleAdd function 應該如下所示:

const handleAdd = () => {
   setTodos(todos => [...todos, { title: title, description: desc }]);
};

If the new state is computed using the previous state, you can pass a function to setState: https://reactjs.org/docs/hooks-reference.html#functional-updates

這可能沒有什么不同,但您不需要在 TextField 組件中創建 function 作為 onChange 的值。 onChange 會將事件傳遞給您的 function ,除非您的 TextField 組件沒有正確處理。 換句話說,TextField 組件的用法應該是這樣的......

<TextField onChange={titleChange} value={title} />

你的 TextField 組件本身應該做這樣的事情......

function TextField({onChange}) {
    function handleChange(event) {
        // Pass the event as an argument into the onChange prop
        onChange(event) 
    }

    return <input onChange={handleChange} />
}

如果您的 TextField 組件是第三方組件,它們至少會傳遞一個值作為參數,因此請檢查這一點。

另一種可能性是您實際上是在 handleAdd function 中更改待辦事項。 如果你想確保 todos 不會發生變異,你可以使用 ES6 向數組添加值的方式......

function handleAdd() {
  setTodos([
    ...todos, 
    {
      title: title,
      description: desc
    }
  ])
}

如果這些都沒有幫助 console.log 你的 todos state 在父組件中,看看它是否正在改變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM