0

我有一个包含 ToDo 列表的组件,上面有一个 SearchBar 来过滤 ToDo。ToDo 存储在 Redux 存储中,因为我在其他组件中也需要它们。但是 SearchTerm 是组件状态的一个属性,因为我只在这个组件中需要它。在componentDidMount钩子中,我调度了一个操作,导致从我的远程服务器获取所有 ToDo。我正在使用mapStateToPropsconnect来自 react-redux。如何在组件中只显示过滤后的 ToDo?在mapStateToProps我无权访问组件状态以使用 SearchTerm 过滤来自 Redux 存储的所有 ToDos 并将过滤的ToDos 道具发送到组件。或者有没有办法订阅组件中对 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)

但是现在,当从服务器获取 toDos 并更新 toDos 属性时,filteredToDos 不会更新。是否有订阅道具更新的钩子或类似的东西?或者我应该将 SearchTerm 放在商店中并mapStateToProps这样写?

class StoreState {
    toDos: string[];
    searchTerm: string;
}

function mapStateToProps(state: StoreState) {
  return { filteredToDos: state.toDos.filter(toDo => toDo.includes(state.searchTerm)) };
}

首选解决方案是什么?

4

0 回答 0