【发布时间】:2021-05-31 09:41:58
【问题描述】:
我需要您的帮助来修复显示基于用户通知状态检查的单选按钮。
我目前遇到的问题是,当我传递isNotification 时,如果不同的键(不同的对象块} 共享相同的值,checked 不会显示在 UI 上。
我想知道为什么会发生这种奇怪的事情,以及我缺少正确显示的内容。
以下是相关代码和截图: Notifications.js:
import React from 'react';
import NotificationForm from './NotificationForm';
class Notifications extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
// get notificationData object from backend
this.props.notificationData.map((section) => this.props.fetchIsNotification(section.slug));
}
render() {
// render empty tags until all API call finishes
if (this.props.notificationData.some((data) => data.isNotification === undefined)) {
return <div />;
}
return (
<section>
<form
action={`/settings/notifications`}
acceptCharset="UTF-8"
method="post"
>
<input type="hidden" />
{this.props.notificationData.map((section) => {
return (
<NotificationForm
key={section.slug}
slug={section.slug}
text={section.caption}
isNotification={section.isNotification}
dispatch={this.props.updateIsNotification}
/>
);
})}
<button type="submit">
Update notification
</button>
</form>
</section>
);
}
}
export default Notifications;
NotificationForm.js:
import React from 'react';
const NotificationForm = ({ text, slug, isNotification, handleUpdate }) => {
return (
<>
<h1>{text}</h1>
<div htmlFor={1}>
<label>
<input
id={1}
type="radio"
name="true"
value="true"
checked={isNotification === true}
onChange={(e) =>
dispatch({
type: 'FETCH_IS_NOTIFICATION_FULFILLED',
payload: e.currentTarget.value,
slug,
})
}
/>
Notify me
</label>
<label htmlFor={2}>
<input
id={2}
type="radio"
name="false"
value="false"
checked={isNotification === false}
onChange={(e) =>
dispatch({
type: 'FETCH_IS_NOTIFICATION_FULFILLED',
payload: e.currentTarget.value,
slug,
})
}
/>
Do not notify me.
</label>
</div>
</>
);
};
export default NotificationForm;
reducer初始状态的this.props.notificationData示例数据:
const initialState = {
notificationData: [
{
slug: 'receive_dm',
caption: 'Whe you received DM',
isNotification: false,
},
{
slug: 'like_comment',
caption: 'When you got like',
isNotification: false,
},
{
slug: 'comment_post',
caption: 'When you got comment',
isNotification: false,
},
{
slug: 'community_post',
caption: 'When someone posted on your community',
isNotification: true,
}
]
};
正如您在屏幕截图中看到的那样,由于带有 receive_dm、link_comment 和 comment_post 的 slug 的对象具有相同的值 isNotification: false,因此不会选中单选按钮。并且 community_post 行被检查,因为 isNotification: true 并且它与其他行的 isNotification 不共享相同的值。
但是我在 receive_dm、link_comment 和 comment_post 的开发工具的输入标签中看到了 checked 属性 ????
【问题讨论】:
标签: reactjs forms redux react-redux radio-button