[英]How to use React.memo with react-redux connect?
有誰知道當使用來自 react-redux 的connect
function 時如何用React.memo
包裝 React 組件?
例如,您將如何修改以下內容?
let Button = (props: Props) => (
<button onClick={props.click}>{props.value}</button>
);
Button = connect(
mapStateToProps,
mapDispatchToProps
)(Button);
我試過了:
let Button = React.memo((props: Props) => (
<button onClick={props.click}>{props.value}</button>
));
Button = connect(
mapStateToProps,
mapDispatchToProps
)(Button);
但是, connect
返回的 function 需要傳遞一個組件,因此它會出錯:
未捕獲的錯誤:您必須將組件傳遞給連接返回的 function。 而是收到 {"compare":null}
React.memo
只是一個HOC,所以你可以使用:
沒有備忘錄:
connect(
mapStateToProps,
mapDispatchToProps
)(Button);
備忘錄:
connect(
mapStateToProps,
mapDispatchToProps
)(React.memo(Button));
甚至包裝連接:(這應該是連接的解決方案)
React.memo(
connect(
mapStateToProps,
mapDispatchToProps
)(Button)
);
就像我們使用withRouter
: withRouter(connect(...)())
同樣的問題在這里 通過將react-redux
升級到版本5.1.0來修復。
您的解決方案應該可以工作(我沒有嘗試像這樣復制粘貼),但您還必須將react-redux
更新到最新版本。
順便說一句,我認為在許多HOC中React.memo
的正確實現將是最接近組件本身: React.memo
的目標是檢查組件接收的所有新道具是否與最后的道具。 如果任何HOC轉換或添加任何道具到組件 - connect
通過將Redux存儲映射到道具, React.memo
應該知道它以決定更新或不更新組件。
所以我會選擇這樣的東西:
//import what you need to import
const Component = props => <div>{/* do what you need to do here */}</div>
export default compose(
connect(mapStateToProps, dispatchToProps),
/* any other HOC*/
React.memo
)(Component);
如錯誤消息所示,您需要將組件從connect
傳遞給返回的函數。
(表示connect()()
的第二對connect()()
)
當React.Memo
返回一個組件時,將其傳遞給connect
的第二個函數。
這是你如何做到這一點。
export const MemoizedDemoComponent = connect(mapStateToProps)(React.memo(DemoComponent);
演示組件:
import React from "react";
import { connect } from "react-redux";
const DemoComponent = props => (
<div>
<p>My demo component fueled by: {props.fuel}!</p>
<p>Redux: {props.state}</p>
</div>
);
const mapStateToProps = state => ({
state: "your redux state..."
});
// create a version that only renders on prop changes
export const MemoizedDemoComponent = connect(mapStateToProps)(
React.memo(DemoComponent)
);
對於工作示例,還要檢查codesandbox 。
對於想知道為什么react-redux
拋出此錯誤的人。
對我來說,我使用了5.0.7
版本, react-redux/src/components/connectAdvanced.js
line: 92
invariant(
typeof WrappedComponent == 'function',
`You must pass a component to the function returned by ` +
`${methodName}. Instead received ${JSON.stringify(WrappedComponent)}`
);
升級后此代碼更改為:
invariant(
isValidElementType(WrappedComponent),
`You must pass a component to the function returned by ` +
`${methodName}. Instead received ${JSON.stringify(WrappedComponent)}`
);
如何檢查WrappedComponent
是否更改為isValidElementType(WrappedComponent)
,它由react-is
公開
因此,紗線至少將 react-redux 更新為@Maxime react-redux
提到的版本
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.