简体   繁体   English

将 prop 设置为 useState 钩子的默认值 ReactJS

[英]Set a prop as the default value of a useState hook ReactJS

I am building a blog with React and MaterialUI that includes a page where all of the posts are displayed.我正在使用 React 和 MaterialUI 构建一个博客,其中包含一个显示所有帖子的页面。 My goal is to be able to click a button to open the "editor mode".我的目标是能够单击一个按钮来打开“编辑器模式”。 I have the buttons working and the editor mode opens successfully.我有按钮工作,编辑器模式成功打开。 When the edior opens, the user has the option of editing the title, the image url and the category.当编辑器打开时,用户可以选择编辑标题、图像 url 和类别。 If the user enters edit mode I would like the text field to populate the current post's title.如果用户进入编辑模式,我希望文本字段填充当前帖子的标题。 Once the title is edited, I would like to save that to a JSON file using the PUT method.编辑标题后,我想使用 PUT 方法将其保存到 JSON 文件中。 Right now, however, my goal is just to set the title to a useState variable.但是,现在我的目标只是将标题设置为 useState 变量。

const [title, setTitle] = useState('');
<TextField label="Post title" variant="outlined" value={post.title} onChange={(e) => setTitle(e.target.value)} fullWidth required />

Right now the value of {post.title} populates the text field, but the useState hook does not update with new data (if changed) after clicking the submit button.现在 {post.title} 的值填充文本字段,但 useState 挂钩在单击提交按钮后不会更新新数据(如果更改)。 I know that the value of the text field must be the state value title, but that does not set the text field to the current value.我知道文本字段的值必须是 state 值标题,但这并没有将文本字段设置为当前值。

Is there a way to set the default state to the value of {post.title} to the text field?有没有办法将默认的 state 设置为文本字段的 {post.title} 值? If not, is there another way to do this?如果没有,还有另一种方法吗?

you are hard coding the value and it doesn't change because post.title never changes.您正在对值进行硬编码并且它不会改变,因为 post.title 永远不会改变。 you should define your state like this你应该这样定义你的 state

const [title, setTitle] = useState(post.title);

and pass the title as the value of your input.并将标题作为输入值传递。

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

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