我有 title
和 message
变量作为我的 React 组件中的本地状态。这个想法是,当组件挂载时,这两个变量要么使用来自 Redux 的 currentPost
对象的各自值初始化,要么使用空字符串初始化。
const MyComponent = ({ currentPost }) => {
const [title, setTitle] = React.useState(currentPost.title ? currentPost.title : '');
const [message, setMessage] = React.useState(currentPost.message ? currentPost.message : '');
<form>
<div className="form-group">
<input
value={title}
onChange={evt => setTitle(evt.target.value)}
/>
</div>
<div className="form-group">
<input
value={title}
onChange={evt => setTitle(evt.target.value)}
/>
</div>
</form>
const mapStateToProps = state => ({ currentPost: state.posts.currentPost });
};
上面的代码实际上是一个模式,每当我点击给定帖子的编辑图标时就会打开它。同时,Redux 状态上的 currentPost
对象(为空)填充所选帖子。然后在上面的模态组件中,我从 Redux 状态获取 currentPost。
问题是这两个变量总是得到一个空字符串,即使 currentPost
填充了我需要的所有数据。如何根据 currentPost 状态使输入字段显示正确的数据?
答案 0 :(得分:1)
试试这个:
const [title, setTitle] = React.useState(
currentPost.title && currentPost.title.length ? currentPost.title : ""
);
const [message, setMessage] = React.useState(
currentPost.message && currentPost.message.length ? currentPost.message : ""
);
currentPost.title 条件检查 title 中是否有值或未定义,如果传递空字符串,则这样的条件将返回 true,以便不仅检查值是否存在,而且同样对于其中存在某些值,您还可以检查长度属性,对于字符串,这应该可以工作。
您可以在此处查看代码:
https://codesandbox.io/s/input-components-o02qg
更新: 看看这个例子,我在 redux 和 TS 上创建了新的 SandBox,
https://codesandbox.io/s/serverless-silence-f19lp?file=/src/MyComponent.tsx
附言只是我不明白为什么要在组件中创建内部状态,如果这些组件的状态存储在 Redux 存储中。
P.P.S.请显示更多代码以了解更多
答案 1 :(得分:1)
你的逻辑是对的,没有错。请注意 useState 只会在组件第一次渲染时定义。您的 redux 状态可能只有在组件已经安装后才会更新。
一种快速检查方法,只需在定义状态之前 console.log
。
const MyComponent = ({ currentPost }) => {
// This will probably show "undefined" in the first log
console.log('current Post', currentPost);
const [title, setTitle] = React.useState(currentPost.title ? currentPost.title : '');
const [message, setMessage] = React.useState(currentPost.message ? currentPost.message : '');
<form>
<div className="form-group">
<input
value={title}
onChange={evt => setTitle(evt.target.value)}
/>
</div>
<div className="form-group">
<input
value={title}
onChange={evt => setTitle(evt.target.value)}
/>
</div>
</form>
const mapStateToProps = state => ({ currentPost: state.posts.currentPost });
};
有两种方法可以解决这个问题。您可以直接在输入中使用 redux 状态,onChange
将调用一个方法来更新相同的状态
或
使用 useEffect
在 currentPost 更改后更新本地状态。
useEffect(() => {
setTitle(currentPost.title);
setMessage(currentPost.message);
}, [currentPost]);