useState在ReactJS中未更新

时间:2020-07-03 08:30:03

标签: reactjs typescript

我有状态

 const [editMode,editModeSwitch]  = React.useState<boolean>(false)

如果editMode为true,但我的按钮似乎没有任何作用,我正在尝试渲染h1, 有什么建议? 这是我的代码:

return (
    editModeSwitch ? (
        <div id="card" className="card">
          <div id="postButtons" className="buttons">
            <button onClick={() => history.push("/homepage")}>Home</button>
            <button onClick={() => history.push("/profile")}>My Profile</button>
            <button onClick={() => LogOut()}>Log Out</button>
          </div>
          <div className="posts">
            <p>
              Title :
              {grabTitleFromLocation()}
            </p>

            <p>
              Description :
              {grabDescriptionFromLocation()}
            </p>
            <button onClick={() => {deletePost(grabIdFromLocation())}}>Delete Post</button>
            <button onClick={() => {editModeSwitch(true)}}>Edit Post</button>
          </div>
        </div>
    ) : (
        <h1>Hello world</h1>
    )
  );
};

2 个答案:

答案 0 :(得分:1)

editModeSwitch是您用来更新editMode的函数。因此,在return语句中应该为editMode,而不是editModeSwitch

return (
  editMode ? ( // update this
    <div id="card" className="card">
      <div id="postButtons" className="buttons">
        <button onClick={() => history.push("/homepage")}>Home</button>
        <button onClick={() => history.push("/profile")}>My Profile</button>
        <button onClick={() => LogOut()}>Log Out</button>
      </div>
      <div className="posts">
        <p>
          Title :
          {grabTitleFromLocation()}
        </p>

        <p>
          Description :
          {grabDescriptionFromLocation()}
        </p>
        <button onClick={() => {deletePost(grabIdFromLocation())}}>Delete Post</button>
        <button onClick={() => {editModeSwitch(true)}}>Edit Post</button>
      </div>
    </div>
  ) : (
    <h1>Hello world</h1>
  )
 );
};

答案 1 :(得分:1)

您使用useState错误

const [editMode,editModeSwitch] = React.useState<boolean>(false)

应该是

const [editMode,setEditMode] = React.useState<boolean>(false)

请在这里https://reactjs.org/docs/hooks-state.html

阅读

更多来自官方文档的示例

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}