我在Youtube上使用React Native + Redux製作簡單的Todo應用程序。如何在子組件中正確使用mapDispatchToProps函數?
添加Todo效果很好。所以我採取了下一步,試圖刪除待辦事項得到了問題。該視頻有點舊,所以版本和平臺(我的Android)是不同的。所以它的方式有點不同...(ES5/ES6等)
無論如何...我想發送動作給調度員使用mapDispatchToProps
的功能,onDeleteTodo
,但它不工作。
首先我嘗試連接組件來存儲,所以添加了行TodoItem = connect(mapStateToProps, mapDispatchToProps)(TodoItem);
。但錯誤仍然存在。
有什麼問題......但我找不到,我該如何解決?
在此先感謝...下面是我的代碼。
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
ScrollView,
TouchableOpacity
} from 'react-native';
import {connect} from 'react-redux';
import {addTodo, deleteTodo} from '../actions';
class TodoItem extends Component {
render() {
return (
// ***************************************
// Below line (onPress prop) is problem.
// when I trying to save todo,
// Error "undefined is not a function (evaluating 'this.props.onDeleteTodo(this.props.id)')
<TouchableOpacity onPress={this.props.onDeleteTodo(this.props.id)}>
<View style={styles.todoContainer}>
<Text style={styles.todoText}>
{this.props.text}
</Text>
</View>
</TouchableOpacity>
)
}
}
TodoItem = connect(
mapStateToProps,
mapDispatchToProps
)(TodoItem);
class Main extends Component {
constructor(props) {
super(props);
this.state = {
newTodoText: ""
}
}
render() {
var renderTodos =() => {
return this.props.todos.map((todo) => {
return (
<TodoItem text={todo.text} key={todo.id} id={todo.id}/>
)
})
};
return (
<View style={styles.wrapper}>
<View style={styles.topBar}>
<Text style={styles.title}>
To-Do List
</Text>
</View>
<View style={styles.inputWrapper}>
<TextInput
onChange={(event) => {
this.setState({
newTodoText: event.nativeEvent.text
});
}}
value={this.state.newTodoText}
returnKeyType="done"
placeholder="New Todo"
onSubmitEditing={
() => {
if(this.state.newTodoText && this.state.newTodoText != ''){
this.props.onAddTodo(this.state.newTodoText);
this.setState({
newTodoText: ''
});
}
}
}
underlineColorAndroid='transparent'
style={styles.input}/>
</View>
<ScrollView
automaticallyAdjustContentInsets={false}>
{renderTodos()}
</ScrollView>
</View>
);
}
}
const mapStateToProps = (state) => {
return {
todos: state.todos
}
};
const mapDispatchToProps = (dispatch) => {
return {
onAddTodo: (todo) => {
dispatch(addTodo(todo))
},
onDeleteTodo: (id) => {
dispatch(deleteTodo(id))
}
}
};
Main = connect(
mapStateToProps,
mapDispatchToProps
)(Main);
export default Main
但** Redux **似乎引人注目地使用這種方式...我認爲它要間接使用調度功能... – Juntae
您添加的代碼位於同一個文件中? 如果是,你應該有單獨的文件中兩個班只爲清晰的代碼... 此外,我定義了一些原型,像這樣: TodoItem.Proptype = { onDeleteTodo = React.Proptype.func, } 有了這個,我會確保函數存在,然後在mapDispatchToProps中定義它... –