gpt4 book ai didi

javascript - React hooks 帮助从基于类的组件进行重构

转载 作者:行者123 更新时间:2023-11-28 03:35:40 24 4
gpt4 key购买 nike

我有一个基于类的组件,我正在尝试重构它以使用钩子(Hook),但遇到了一些我无法弄清楚的麻烦。我有一个调查问题组件,它将根据创建的问题类型显示一个下拉框、复选框等。但是,当出现新问题时,我似乎无法弄清楚在哪里可以重新初始化基础值。任何帮助是极大的赞赏。我只显示复选框组件功能。

const CheckboxButton = ({ onClick, checked, label }) => {
return (
<TouchableOpacity
style={checkboxStyles.wrapper}
activeOpacity={1}
onPress={() => {
if (typeof onClick === 'function') {
onClick(!checked);
}
}}
>
<View
style={[
checkboxStyles.checkbox,
checked ? checkboxStyles.checkboxChecked : null
]}
>
{checked ? <View style={checkboxStyles.checkboxCheckedDot} /> : null}
</View>
<Text style={checkboxStyles.label}>{label}</Text>
</TouchableOpacity>
);
};

const QuestionCheckboxes = ({ question, onChange }) => {
const [checkedIndex, setCheckedIndex] = useState([]);

const _onChange = checked => {
const options = question.options;
let values = [];

for (let i in checked) {
if (checked[i]) {
values.push(options[i]);
}
}

if (typeof onChange === 'function') {
onChange(values.length ? values : null);
}
};

let items = [];
for (let i = 0; i < question.options.length; ++i) {
const option = question.options[i];
items.push(
<CheckboxButton
key={i}
label={option}
checked={checkedIndex[i]}
onClick={value => {
let newCheckedIndex = [...checkedIndex];
newCheckedIndex[i] = value;
setCheckedIndex(newCheckedIndex);
//need to use newCheckedIndex for onChange b/c checked index has been set
_onChange(newCheckedIndex);
}}
/>
);
}

return <View>{items}</View>;
};

const QuestionView = ({ index, question, onChange }) => {
const questionComponents = {
dropdown: QuestionDropdown,
radios: QuestionRadios,
checkboxes: QuestionCheckboxes,
stars: QuestionStars
};

if (typeof questionComponents[question.type] !== 'function') {
return null;
}

const QuestionComponent = questionComponents[question.type];

return (
<View>
<Text style={styles.questionTitle}>
{index}. {question.title}
</Text>
<View style={styles.questionComponent}>
<QuestionComponent question={question} onChange={onChange} />
</View>
</View>
);
};

const SurveyQuestion = ({ navigation }) => {

const [survey, setSurvey] = useState(navigation.getParam('item'));
const questionsCount = survey.entity.data.length;
const [current, setCurrent] = useState(0);
const [index, setIndex] = useState(1);
const [progress, setProgress] = useState(index / questionsCount);
const [answers, setAnswers] = useState([]);

_nextQuestion = async () => {
setProgress(index / questionsCount);
if (typeof answers[current] === 'undefined' || answers[current] === null) {
// GeneralActions.notify('Please answer this question.');
console.log('did not answer question');
return;
}

if (current === survey.entity.data.length - 1) {
console.log('getting ready to send to server');
try {
const response = await axios.post('/request', {
id: survey.id,
key: null,
data: answers
});
} catch (err) {
console.log('error posting survey: ', err);
}
return null;
}
setCurrent(current + 1);
setIndex(index + 1);
};

return (
<ScrollView style={styles.container}>
<View style={styles.container}>
<View style={styles.questions}>
<View style={styles.progressbar}>
<ProgressBar
progress={progress}
width={null}
height={20}
borderRadius={10}
borderWidth={0}
unfilledColor='#f5f5f5'
/>
</View>
<Text style={styles.questionsInfo}>
{index} / {questionsCount}
</Text>
</View>
<View style={styles.questionWrapper}>
<QuestionView
index={index}
question={survey.entity.data[current]}
onChange={value => {
let newAnswers = answers.slice();
newAnswers[current] = value;
setAnswers(newAnswers);
}}
/>
</View>
<View style={styles.action}>
<TouchableOpacity
style={styles.buttonPrimary}
activeOpacity={0.7}
onPress={_nextQuestion}
>
<Text style={styles.button}>
{progress === 1 ? 'FINISH' : 'NEXT'}
</Text>
</TouchableOpacity>
</View>
</View>
</ScrollView>
);
};

目前,当我从一个问题转到另一个问题时,旧的答案将继续存在。例如,我不知道在哪里可以将checkedIndex重新初始化回[]。

const [checkedIndex, setCheckedIndex] = useState([]);

我尝试将 setCheckedIndex([]) 放在几个区域中,但重新渲染次数过多。

最佳答案

这可能是因为它在每次渲染之间重用相同的 QuestionComponent 组件。我无法测试它,但我会尝试添加一个唯一的键来向 React 提供“提示”,即只要键发生变化,它就应该创建一个新组件。

<QuestionComponent
key={question.uniqueIdOrSomething}
question={question}
onChange={onChange}
/>;

其中 uniqueIdOrSomething 可以是问题 id 或问题 text(任何可以唯一标识问题的内容)。

通常,key 在列表中使用,因此如果顺序发生变化,React 可以重用组件(性能优化)。然而,它也可以用来告诉 React 这个组件是不同的,并且它不应该重用现有组件并重新实例化它。对于您来说,这将删除现有状态并为您提供新的默认值。我认为这是使用 key 的正确用例,但要小心过度使用这种方法(添加 key 属性),因为它可能会掩盖其他问题。

有关 key 属性的更多详细信息:https://reactjs.org/docs/lists-and-keys.html

关于javascript - React hooks 帮助从基于类的组件进行重构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764745/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com