我正在制作一个应用程序的前端,该应用程序使用React.js来控制家用电器。
我想将从后端获得的相机位置反映到单选按钮
下面是代码,但是单选按钮没有选中,我不知道原因。输入图片描述
在控制台中,我可以看到camera_position变量中的信息。输入图片描述 Json
{
"attributes": {
"camera": [
{
"entity_id": "camera_2",
"mode": "Away",
"state": "Away",
},
],
}
React.js
const { entity_id } = useParams();
const [camera_position, setCameraPosition] = useState();
const getDevices = async(data) => {
await axios.get('xxx.com',
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
console.log(result.data)
setCamera(result.data.attributes.camera);
setCameraPosition(result.data.attributes.camera.filter(c => c.entity_id === entity_id).map((item,i) => item.mode));
})
.catch(err => {
console.log(err);
});
}
const setCameraHome = async(data) => {
await axios.post('xxx.com/camera/set_home',
{
entity_id: entity_id,
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
console.log(result.data)
console.log('Set Home!');
setCameraPosition('Home');
getDevices();
})
.catch(err => {
console.log('Missed Set Home!');
console.log(err);
});
}
const setCameraAway = async(data) => {
await axios.post('xxx.com/camera/set_away',
{
entity_id: entity_id,
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${cookies.get('accesstoken')}`
},
})
.then(result => {
console.log(result.data)
console.log('Set Away!');
setCameraPosition('Away');
getDevices();
})
.catch(err => {
console.log('Missed Set Away!');
console.log(err);
});
}
return (
<div>
<input
type="radio"
value="Home"
onChange={setCameraHome}
checked={camera_position === 'Home'}
/>
<input
type="radio"
value="Away"
onChange={setCameraAway}
checked={camera_position === 'Away'}
/>
</div>
)
这一行:
setCameraPosition(result.data.attributes.camera.filter(c => c.entity_id === entity_id).map((item,i) => item.mode));
map
将返回一个数组[]
并将其设置在camera_position
中。不是字符串
你必须使用索引来访问它,或者在选中的属性中处理数组。
<div>
<input
type="radio"
value="Home"
onChange={setCameraHome}
checked={camera_position[0] === 'Home'}
/>
<input
type="radio"
value="Away"
onChange={setCameraAway}
checked={camera_position[0] === 'Away'}
/>
</div>
工作!