[英]I don't know why rendering doesn't work in react
This code is TODO APP which can add, and delete Note.此代码为TODO APP,可添加、删除Note。 However, when I run this code, It works 'Add' function , but when I try to delete note, It doesn't delete the note immediately.
但是,当我运行此代码时,它可以使用“添加”功能,但是当我尝试删除注释时,它不会立即删除注释。 And when I write any word on TextInput, then it deletes the note that I tried to delete.
当我在 TextInput 上写任何字时,它会删除我试图删除的笔记。
export function Note(props){
return (
<View>
<View>
<Text>{props.val.date}</Text>
<Text>{props.val.note}</Text>
</View>
<TouchableOpacity onPress={props.deleteMethod}>
<Text>D</Text>
</TouchableOpacity>
</View>
);
}
export function MyqtwriteScreen({ navigation, route }) {
const [noteArray, setNoteArray] = useState([]);
const [noteText, setNoteText] = useState('');
let notes = noteArray.map((val, key) => {
console.log('start');
return <Note key={key} keyval={key} val={val}
deleteMethod={() => deleteNote(key)} />
});
const addNote = ()=>{
if (noteText) {
var d = new Date();
noteArray.push({
'date': d.getFullYear() +
"/" + (d.getMonth() + 1) +
"/" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes(),
'note': noteText,
});
setNoteArray(noteArray);
setNoteText('');
}
};
const deleteNote = (key)=> {
noteArray.splice(key, 1);
setNoteArray(noteArray);
// setNoteText('');
};
return (
<View style={styles.container}>
<View>
{notes}
</View>
<TextInput
onChangeText={(noteText) => setNoteText(noteText)}
value={noteText}
placeholder='>>>note'
placeholderTextColor='gray'
></TextInput>
<TouchableOpacity onPress={addNote}>
<Text>+</Text>
</TouchableOpacity>
</View>
);
}
I don't know why rendering doesn't work!我不知道为什么渲染不起作用! I'm struggling this problem for over 2days... Please Help me.....
我在这个问题上挣扎了超过 2 天...请帮帮我.....
Splice updates the actual array, for a component to rerender the array should be replaced by a new instance. Splice 更新实际数组,对于重新渲染数组的组件应该由新实例替换。
const deleteNote = (key)=> {
const newArray=[...noteArray];
newArray.splice(key, 1);
setNoteArray(newArray);
};
By this it will be pointed to a new array.这样,它将指向一个新数组。
The reason for it to update when you change the text is the text causes a re render as the state is updated.当您更改文本时它更新的原因是文本会在状态更新时导致重新渲染。 You can also consider using the filter function of the array.
也可以考虑使用数组的过滤功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.