gpt4 book ai didi

reactjs - 在 redux 工具包中使用 dispatch 发送多个 Action

转载 作者:行者123 更新时间:2023-12-05 04:21:24 32 4
gpt4 key购买 nike

我是 Redux 和 redux 工具包的新手。我正在制作待办事项应用程序来学习它。在那里我可以添加和删除待办事项。现在我正在尝试编辑它。但是我不知道如何发送我添加到我的文本输入的文本的有效负载(那个是"new"待办事项)和 key ,所以我知道我按下了哪一个。也许我遗漏了一些简单的东西,或者我需要了解一些我误解了的东西?希望我的代码理解起来不会太乱,谢谢。

这是我的切片:

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>
)
}

最佳答案

@Rashomon 给出了答案。 “您的操作的有效负载应该是一个包含键和文本的对象。例如:{key: 1, text: "edited todo"}。”

关于reactjs - 在 redux 工具包中使用 dispatch 发送多个 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74211021/

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