0

因此,我阅读了许多似乎与我涵盖相同主题的帖子,但是在尝试了他们所有的解决方案之后,我根本无法使其工作,所以就这样吧。

我有一个简单的搜索过滤器,我用它来按名称过滤一些食谱。我有一个 Redux Store 来处理搜索过滤器的状态(值)。在输入字段中输入值时,我的操作对 reducer 很好,它会更新状态(我可以通过 console.logs 和 Redux DevTools 看到这一点)。但不知何故,这不会更新我的道具,这些道具是用 connect 和 mapStateToProps 映射的

我遇到的所有以前的答案都指向变异状态,但是我尝试过我的减速器的多次迭代,但话又说回来,我可能只是忽略了一些东西。

我的过滤器动作调度:

filter(e){
    Store.dispatch({
        type: 'SET_NAME_FILTER',
        payload: e.target.value
    })
}

我的减速机:

const filterNameReducer = (state = [""], action) => {
    if (action.type === 'SET_NAME_FILTER') {
        return [
            action.payload
        ];
    }
    return state;
}

我的食谱列表容器:

class RecipeListContainer extends React.Component {    
    render() {
        return (
            <RecipeList recipes={ this.props.recipes } filterName={ this.props.filterName }/>
        )
    }
}
const mapStateToProps = (state) => {
    return {
        filterName: state.filterNameState,
    }
}
module.exports = connect(mapStateToProps)(RecipeListContainer)

我的 RecipeList 组件:

class RecipeList extends React.Component {
    render() {
        return (
            <ul>
                {this.props.recipes.filter(this.filters, this).map(({ node: recipe }) => {
                    return (
                        <RecipeListItem key={ recipe.id } id={ recipe.id } value={ 0 } name={ recipe.name } time={ recipe.time } type={ recipe.type } tags={ recipe.tags } ingredients={ recipe.ingredients } />
                    );
                })}
            </ul>
        )
    }
    filters() {
        if (this.props.filterName[0].length != 0) {
           return true;
        } else {
           return false;
        }
    }
}

我知道我的过滤器还没有做那么多,但我已经让它变得简单了,所以我可以看看它是否得到了更新。如果我更改减速器的初始值,它会正确过滤。所以不应该这样。

另外,我在 GatsbyJS 中使用它,但根据他们的文档和示例,这应该不是问题。但我可能是错的?

提前非常感谢!如果我错过了一些让您找到解决方案的东西,请告诉我,我是在 SO 上发帖的新手。

4

0 回答 0