我目前正在尝试学习Redux,但我在使用Redux管理状态时遇到了麻烦。现在我可以使用useState来管理状态,它可以工作,但使用Redux无法计算出它。现在我的应用程序只是试图在输入字段中输入文本,当按下按钮时,它会将其添加到平面列表状态。
import { connect } from 'react-redux';
import {View,Text,Button,TextInput,FlatList,ScrollView,} from 'react-native';
import { useState } from 'react';
import { Add_Item } from '../redux/actions/index';
const mapStateToProps = (state) => {
return { tasks: state.reducer.tasks };
};
const mapDispatchToProps = { Add_Item };
function App({ tasks, Add_Item }) {
const [add, setAdd] = useState('');
return (
<ScrollView>
<View style={{paddingTop: 20}}>
<View style={{ border: '2px solid green', margin: 10 }}>
<TextInput
placeholder="Enter Value Here"
onChangeText={(add) => setAdd(add)}
/>
</View>
<View
style={{
padding: 3,
border: '2px solid green',
backgroundColor: 'green',
'border-radius': 15,
margin: 10,
}}>
<Button
title="Add Values to Flatlist"
onPress={() => Add_Item(add)}
color="green"
/>
</View>
<FlatList
data={tasks}
renderItem={({ item }) => (
<View>
<Text
style={{
borderBottomColor: 'grey',
borderBottomWidth: 1,
padding: 5,
}}>
{item.title}
</Text>
</View>
)}
/>
</View>
</ScrollView>
);
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
我的文本转换器文件:
import { ADD_ITEM } from '../actionType/index';
var initialState = {
tasks: [],
};
export default function (state = initialState, action) {
if (action.type == ADD_ITEM) {
return {...state,
tasks: [...state.tasks,{title:action.payload.title}]}
}
return state;
}
我的存储文件:
import { configureStore } from "@reduxjs/toolkit";
import reducer from "../reducers/index";
export default configureStore({reducer});
我的app. js:
import React, { useState } from 'react';
import { View } from 'react-native';
import {Provider} from 'react-redux';
import store from './redux/store/index';
import AddApp from './FlatListApp/index'
export default function App() {
return (
<Provider store={store}>
<AddApp/>
</Provider>
);
}
1条答案
按热度按时间lymnna711#
问题是您正在mapDispatchToProps和App中使用
Add_Item
本身,您必须在mapDispatchToProps中重命名Add_Item
,然后在App中使用它:但是我建议您使用钩子而不是connect,redux团队也建议您使用redux工具包。