reactjs - React Native - 使用 Redux 将项目添加到 FlatList
问题描述
我正在尝试使用 Redux 实现一个简单的 ToDo 列表练习应用程序。
我有 a TextInput
、 aButton
和 a FlatList
,这些项目作为数组存储在a 中store
并由 a 处理reducer
。按下按钮时,应将带有输入文本的项目添加到列表中。
目前,当我按下按钮时,没有任何反应,列表似乎没有呈现,也没有添加新元素。我怀疑 onPress 处理可能有问题,但我不确定,我可能在其他地方犯了错误,我对 React Native 很陌生
欢迎任何帮助解决这个问题。
到目前为止,这是我的代码(没有导入):
行动
export const addItem = item =>({type: ADD_ITEM, payload: item});
减速器
const initialState = {
items: [],
};
const itemReducer = (state = initialState, action) => {
switch(action.type) {
case ADD_ITEM:
return { ...state, items: [...state.items, action.payload] };
default:
return state;
}
};
export default itemReducer;
店铺
const store = createStore(itemReducer);
export default store;
输入表格
const mapDispatchToProps = dispatch => {
return {
addItem: item => dispatch(addItem(item))
};
};
class ItemInput extends Component {
constructor(props) {
super(props);
this.state = { itemText: 'Add an item' };
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit() {
//event.preventDefault();
const { itemText } = this.state;
this.props.addItem( { itemText } );
this.setState({ itemText: "" });
}
render() {
return (
<View>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(itemText) => this.setState({itemText})}
value={this.state.itemText}
/>
<Button
onPress={this.handleSubmit}
title="Submit"
color="#841584"
/>
</View>
);
}
}
export default ItemInput = connect(null, mapDispatchToProps)(ItemInput);
列表
const mapStateToProps = state => {
return { items: state.items };
};
class ItemList extends Component {
constructor(props) {
super(props);
this.state = {
};
this.renderItem = this.renderItem.bind(this);
this.keyExtractor = this.keyExtractor.bind(this);
}
render() {
return (
<View style={{flex:1, backgroundColor: '#F5F5F5', paddingTop:20}}>
<FlatList
ref='listRef'
data={this.props.items}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}/>
</View>
);
}
keyExtractor = (item, index) => index.toString();
renderItem({item, index}) {
return (
<View style={{backgroundColor: 'white'}}>
<Text>{item.title}</Text>
</View>
)
}
}
export default List = connect(mapStateToProps)(ItemList);
待办事项列表组件
class ToDoList extends Component {
render() {
return (
<View>
<ItemInput/>
<List/>
</View>
);
}
}
export default ToDoList;
应用程序(根)
export default class App extends Component {
render() {
return (
<Provider store={store}>
<ToDoList/>
</Provider>
);
}
}
解决方案
推荐阅读
- installshield - Installshield:由于合并模块导致文件重复
- spring-boot - 多数据源配置的 Spring Boot 1.5.18 无法使用 HikariCP
- javascript - 如何等待 window.performance.timing 中的所有值都被定义
- xamarin - 使用 Environment 访问 Android 特殊文件夹路径
- python - matplotlib:多个子图未强制执行轴刻度标签对齐
- xcode - Xcode watch '无效的表达式'
- c# - XmlReader - 如何在没有 System.OutOfMemoryException 的情况下读取元素中很长的字符串
- c++ - 如何将指向指针列表的私有指针作为const返回?
- git - Windows 10 上的 Git Bash 忽略 Ctrl + C
- ios - 为原生 iOS 应用程序创建 Jitsi Meet 框架并集成到 Xcode 项目中