问题描述
我有一个带有待办事项列表的组件,上面有一个SearchBar来过滤待办事项。待办事项存储在Redux存储中,因为我在其他组件中也需要它们。但是SearchTerm是组件状态的属性,因为我仅在此组件中需要它。在componentDidMount
钩子中,我调度了一个导致从远程服务器获取所有待办事项的操作。我正在使用react-redux中的mapStatetoProps
和connect
。如何仅在组件中显示经过筛选的待办事项?在mapStatetoProps
中,我无权访问组件状态以使用SearchTerm过滤Redux存储中的所有Todos并将filterTodos prop发送到组件。还是有一种方法可以订阅对组件中Todos道具所做的更改,以便在从服务器中获取Todos时可以对它们进行过滤?还是应该将SearchTerm放在redux存储中,以便可以在mapStatetoProps
函数中访问它?什么是最干净的解决方案?
这是一些代码来说明问题:
class StoreState {
todos: string[];
}
class TodoList extends Component {
constructor(props) {
super(props);
this.state = { searchTerm: '',filteredTodos: [] };
}
componentDidMount() {
this.props.dispatch(fetchAllTodos());
}
handleChangeText(searchTerm: string) {
const filteredTodos = this.props.todos.filter(todo => todo.includes(searchTerm));
this.setState({ searchTerm,filteredTodos });
}
render() {
return (
<View>
<TextInput onChangeText={ searchTerm => this.handleChangeText(searchTerm) } /> // SearchBar
<FlatList data={this.state.filteredTodos}/> // List of filtered todo items
</View>
);
}
}
function mapStatetoProps(state: StoreState) {
return { todos: state.todos };
}
export default connect(mapStatetoProps)(TodoList)
但是,现在,当从服务器获取待办事项并且待办事项更新时,filteredTodos也不会更新。是否有一个钩子或类似的东西来订阅道具更新?还是应该将SearchTerm放在商店中,然后这样写mapStatetoProps
?
class StoreState {
todos: string[];
searchTerm: string;
}
function mapStatetoProps(state: StoreState) {
return { filteredTodos: state.todos.filter(todo => todo.includes(state.searchTerm)) };
}
首选解决方案是什么?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)