我是Redux和Redux工具包的新手。我正在制作一个todo应用程序来学习它。在那里我可以添加和删除todos。现在我正在尝试编辑它。但是我不知道如何发送我添加到我的textinput中的文本的有效载荷(“新”待办事项)和键,这样我就知道我按了哪个键。也许我错过了一些简单的东西,或者有什么我需要学习的东西,我'我误会了?希望我的代码不会太混乱,谢谢。
"这是我的一片“
export const todoSlice = createSlice({
name: "todo",
initialState:{todos:[{text:"test1", key:1}, {text:"test2", key:2}, {text:"test3", key:3}]},
reducers: {
addTodo: (state, action) => {
const todo = {key: Math.random(), text: action.payload,};
state.todos.push(todo);
},
removeTodo: (state, action) => {
state.todos = state.todos.filter((todo) => todo.key !== action.payload);
},
clearAll: (state) => {
state.todos = []
},
editTodo:(state, action) => {
//This is where I want to update the text
}
},
});
这是应用程序:
export default function Home() {
const [text, setText] = useState("")
const [showModal, setShowModal] = useState(false)
const [modalText, setModalText] = useState()
const [newText, setNewText] = useState("")
const [currentItem, setCurrentItem] = useState()
const todos = useSelector((state) => state.todo.todos);
const dispatch = useDispatch();
const handleOnChangeText = (val) => {
setText(val)
}
const handleAddTodo = () => {
if (text.length > 0){
dispatch(addTodo(text))
setText("")
} else {
console.log("error")
}
}
const handleRemoveTodo = (item) => {
dispatch(removeTodo(item.key))
}
const handleClearAll = () => {
dispatch(clearAll())
}
const handleOnEditPress = (item) => {
setModalText(item.text)
setShowModal(true)
setCurrentItem(item)
}
const handleEditTodoText = (val) => {
setNewText(val)
}
const handleOnSavePress = () => {
dispatch(editTodo(newText))
}
return (
<SafeAreaView style={styles.container}>
{ showModal ? <EditModule
onClosePress={()=>setShowModal(false)}
title={modalText}
placeholder={modalText}
onChangeText={(val)=>handleEditTodoText(val)}
onSavePress={()=>handleOnSavePress()}
/> : null}
<View style={styles.topSection}>
<Text>Add text</Text>
<TextInput
placeholder='Write here'
style={styles.textinput}
onChangeText={(val)=>handleOnChangeText(val)}
value={text}
onBlur={()=>handleAddTodo()}
/>
<Button
text={"Add"}
onPress={()=>handleAddTodo()}
/>
<Button
text={"Clear all"}
onPress={()=>handleClearAll()}
/>
</View>
<View style={styles.bottomSection}>
<FlatList
data={todos}
renderItem={ ({item}) => (
<ListItem
text={item.text}
onPress={()=>handleRemoveTodo(item)}
onEditPress={()=>handleOnEditPress(item)}
/>)}
/>
</View>
</SafeAreaView>
)
}
1条答案
按热度按时间alen0pnh1#
@Rashomon给出了答案,“你的动作的有效载荷应该是一个包含密钥和文本的对象,例如:{键:1,文本:“已编辑待办事项”}”。