react-native - 无法在反应原生项目中使用 redux 管理状态
问题描述
我是反应原生开发的新手。我已经使用 Redux 创建了这个示例笔记应用程序来进行本机反应。在此应用程序中,用户必须能够添加注释,并且该注释需要通过 redux 存储进行管理。我已经创建了添加注释功能所需的操作和减速器。但是,我无法向商店添加新注释。我尝试调试,当它到达减速器中的“ADD_Note”案例时,它会自动跳转到默认案例。无论通过动作传递的字符串值或注释,它在减速器中都变成“未定义”。
请参考我的代码以添加注释屏幕
import React, {useState, useEffect} from 'react';
import {
StyleSheet,
View,
Text,
TextInput,
Button,
FlatList,
} from 'react-native';
import {useSelector, useDispatch} from 'react-redux';
import * as NoteActions from '../store/actions/Note'; // import note actions
const NoteScreen = () => {
const [note, setNote] = useState('');
const dispatch = useDispatch(); // use dispatch
const noteHandler = text => {
setNote(text);
};
return (
<View style={styles.container}>
<View>
<TextInput
style={styles.textInput}
placeholder="Enter a note"
onChangeText={noteHandler}
value={note}
/>
<Button
title="Add"
onPress={() => {
console.log(note);
dispatch(NoteActions.addNote(note));
}}
/>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
width: '100%',
margin: 10,
},
textInput: {
width: '100%',
marginBottom: 10,
textAlign: 'center',
borderBottomWidth: 1,
},
});
export default NoteScreen;
下面是动作js文件。
// action types
export const ADD_NOTE = 'ADD_NOTE'
//action creators
export function addNote(note){
return{
type:ADD_NOTE,
date:note
}
}
下面是reducer js文件
// initial state
const initialState ={
noteList:[]
}
// import actions
import ADD_NOTE from '../actions/Note';
function noteReducer (state=initialState, action){
debugger;
switch(action.type){
case ADD_NOTE:
const newNote = action.data
return{
...state,
noteList: state.noteList, newNote
}
default:
return state;
}
}
导出默认noteReducer;
请帮我。
提前致谢, 约汉
解决方案
您需要dispatch
在您的操作中添加图层,还要注意错字日期而不是数据
export const addNote = (note) => (dispatch, getState) => {
return dispatch({
type:ADD_NOTE,
data :note
})
}