我的组件具有三个选项卡,每个选项卡都有唯一的过滤器。我目前正在编写一个过滤器组件,该组件将作为Prop中的Tab类型并渲染正确的过滤器按钮。单击每个按钮后,我希望按钮样式更改,以便用户知道他们已经设置了给定的过滤器。
我正在将每个按钮的状态存储在下面定义的对象中:
const [filterState, setFilterState] = useState({
deployment: {
running: false,
success: false,
warnings: false,
failures: false,
},
health: {
warnings: false,
critical: false,
errors: false,
},
task: {
waiting: false,
running: false,
retrying: false,
success: false,
failures: false,
}
})
我有一个辅助功能来设置这样定义的滤镜状态:
const setFilter = tab => {
let updateFilter = filterState
updateFilter[umsTab][tab] = !filterState[umsTab][tab]
setFilterState(updateFilter)
console.log(filterState[umsTab])
}
我这样做,这样每次调用此功能时,我都会完全更新对象状态。按钮组件中的OnClick方法将调用用于更新状态的功能。这些按钮组件是在我上面提到的动态创建的,如:
const createButtons = () => {
let FilterButtons = []
FilterTypes[umsTab].forEach(tab => {
FilterButtons.push(
<Button
kind={filterState[umsTab][tab] === false ? "primary" : "secondary"}
key={tab}
onClick={() => setFilter(tab)}
>
{tab}
</Button>
)
})
return FilterButtons
}
单击按钮并记录控制台中的FilterType状态变量,显示该状态正在更新,但是组件没有重新启动。由于按钮是动态创建的事实,是否可以在此处输入代码?我希望通过检查状态对象,每次点击时都可以使用或不使用样式化的按钮。
完整代码:
const FilterTypes = {
deployment: ["running", "success", "warnings", "failures"],
health: ["warnings", "critical", "errors"],
task: ["waiting", "running", "retrying", "success", "failures"],
}
const Filters = ({ umsTab }: Props) => {
const { message } = useMessages()
const [filterState, setFilterState] = useState({
deployment: {
running: false,
success: false,
warnings: false,
failures: false,
},
health: {
warnings: false,
critical: false,
errors: false,
},
task: {
waiting: false,
running: false,
retrying: false,
success: false,
failures: false,
},
})
const setFilter = tab => {
let updateFilter = filterState
updateFilter[umsTab][tab] = !filterState[umsTab][tab]
setFilterState(updateFilter)
console.log(filterState[umsTab])
}
const createButtons = () => {
let FilterButtons = []
FilterTypes[umsTab].forEach(tab => {
FilterButtons.push(
<Button
kind={filterState[umsTab][tab] === false ? "primary" : "secondary"}
key={tab}
onClick={() => setFilter(tab)}
>
{tab}
</Button>
)
})
return FilterButtons
}
return <div>{createButtons()}</div>
}
尝试将CreateButtons方法重构为组件函数,并提供所使用的字段作为属性。当调用渲染函数中的函数无法检查是否更改了某些使用的值,也无法正确更新Shadowdom
const CreateButtons = ({filterTypes, filterState, umsTab}) => (
<React.Fragment>
{filterTypes[umsTab].map(tab => (
<Button
kind={filterState[umsTab][tab] === false ? "primary" : "secondary"}
key={tab}
onClick={() => setFilter(tab)}
>
{tab}
</Button>
))
}
</React.Fragment>
)
和过滤器
return <div><CreateButtons filterTypes={FilterTypes} filterState={filterState} umsTab={umsTab}/></div>