【发布时间】:2021-01-11 00:30:18
【问题描述】:
我有一些从 Array.map() 中渲染的组件,即使状态(与所述数组有关)发生变化也不会更新,我不知道为什么会这样。
首页(主要组件):
import React, { useState } from 'react';
import { View, TouchableOpacity } from 'react-native';
import { base } from './data';
import Indicator from './components/Indicator';
const Home = () => {
const [switches, setSwitches] = useState(base);
const handleToggle = (id: number) => {
base.map(switch => {
switch.on =
(switch.on && switch.id !== id) || (!switch.on && switch.id === id)
? !switch.on
: switch.on;
});
setSwitches(base);
};
return (
<View>
{switches.map(switch => (
<TouchableOpacity
onPress={() => handleToggle(switch.id)}
key={switch.id}
>
<Indicator
color={switch.color}
on={switch.on}
/>
</TouchableOpacity>
))}
</View>
指标组件:
import React from 'react';
import { View } from 'react-native';
import { On, Off } from './Indicators';
interface IndicatorProps {
color: string;
on: boolean;
}
const Indicator: React.FC<IndicatorProps> = ({ color, on }) => {
return (
<View>
{on ? <On /> : <Off />}
</View>
);
};
export default Indicator;
我已验证switches 的状态在单击可触摸区域时按预期发生变化,但组件中没有发生可见变化。
【问题讨论】:
标签: typescript react-native react-typescript