React Hooks:有条件地渲染组件,但可以访问整个状态

时间:2020-06-25 11:42:01

标签: javascript reactjs redux react-hooks

假设我的状态由这样的对象表示:

state = {
    array: [1, 2, 3, 4, 5]
}

我知道我是否使用:

const state = useSelector(state => state.array)

每次数组的元素之一更改时,我的组件都会重新渲染,但是我不想要它。因此,解决方案可以是:

state = {
    render: false,
    array: [1, 2, 3, 4, 5]
}

现在我可以:

const state = useSelector(state => state.render)

并通过有条件地分派一些操作来处理渲染。但是以这种方式,我再也无法访问数组了。 这里的问题是,在我的项目中,是每次阵列更新时都需要重新渲染的组件,以及仅在特定情况下才需要重新渲染的组件。另一个解决方案是只为很少需要重新渲染的组件创建另一个存储,但这似乎对我来说太有线了。

1 个答案:

答案 0 :(得分:3)

{ "type": "AdaptiveCard", "body": [ { "type": "Container", "style": "emphasis", "items": [ { "type": "ColumnSet", "columns": [ { "type": "Column", "items": [ { "type": "TextBlock", "size": "Large", "weight": "Bolder", "text": "**PART APPROVAL**" } ], "width": "stretch" } ] } ], "bleed": true }, { "type": "Container", "items": [ { "type": "ColumnSet", "columns": [ { "type": "Column", "items": [ { "type": "TextBlock", "size": "ExtraLarge", "text": "New Part Approval", "wrap": true } ], "width": "stretch" } ] }, { "type": "FactSet", "spacing": "Large", "facts": [ { "title": "Part #:", "value": "**@{items('Apply_to_each')?['Part Number']}**" }, { "title": "Description:", "value": "@{items('Apply_to_each')?['Description']}" }, { "title": "Quantity:", "value": "@{items('Apply_to_each')?['AOQ']}" }, { "title": "Cost Each:", "value": "@{items('Apply_to_each')?['Cost Each']}" }, { "title": "Sell Each:", "value": "@{items('Apply_to_each')?['Sell Each']}" } ] } ] }, { "type": "Container", "items": [ { "type": "ActionSet", "actions": [ { "type": "Action.Submit", "title": "Approve", "style": "positive", "data": { "id": "_qkQW8dJlUeLVi7ZMEzYVw", "action": "approve" }, "id": "ApproveID" }, { "type": "Action.ShowCard", "title": "Reject", "style": "destructive", "card": { "type": "AdaptiveCard", "body": [ { "type": "Input.Text", "id": "RejectCommentID", "placeholder": "Please specify an appropriate reason for rejection.", "isMultiline": true } ], "actions": [ { "type": "Action.Submit", "title": "Send", "data": { "id": "_qkQ8dJlUeMVi7ZMEzYVf", "action": "reject" } } ], "$schema": "http://adaptivecards.io/schemas/adaptive-card.json" }, "id": "RejectID" } ] } ] } ], "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", "version": "1.2", "fallbackText": "This card requires Adaptive Cards v1.2 support to be rendered properly." } 接受a second argument equlityFn

useSelector

如果const result: any = useSelector(selector: Function, equalityFn?: Function) 返回equlityFn,则没有准确的订阅更新,因此不会由选择器生成渲染。

true