React-Redux-Hooks API


9

我正在尝试配置新的react-redux应用程序以使用React-Redux的新功能。在官方文件说:

React Redux现在提供了一组钩子API,以替代现有的connect()高阶组件。

我一直在尝试找到一些与Hooks API相关的帮助文章,并提供一些实际示例,但是所有react-redux Apps都在使用connect函数。官方文档还显示了非常基本的示例。

我想使用useSelector(由Hooks API提供)更改应用程序中的连接功能。

这是我的应用程序中的示例代码片段。

//MessagesListContainer
export default connect(
  // mapStateToProps
  (state:State) => ({
    activeUser: getActiveUser(state),   
    messages: getMessagesList(state),   
  })
)(MessagesList)

//Selectors
export const getActiveUser = (state: State) => state.activeUser;
export const getMessagesList = (state : State) => (
  Object.keys(state.messages).map((key : any)=> state.messages[key])
)

export interface IMessagesListProps {
  activeUser?: User;
  messages?: Message[];
}
/**
 *  Messages List
 */
export default class MessagesList extends PureComponent<IMessagesListProps> {
.
.
.
}

Answers:


11

挂钩与Class组件不兼容。要使用挂钩,您需要将类组件转换为功能组件。例如,您的代码可以重构为

/**
 *  Messages List
 */

const getActiveUser = (state: State) => state.activeUser;
const getMessagesList = (state : State) => (Object.keys(state.messages).map((key : any)=> state.messages[key]));

const MessagesList: React.FC = () => {
  const activeUser = useSelector(getActiveUser);
  const messagesList = useSelector(getMessagesList);

  ....
}

export default MessagesList;

0

Hooks API简化了功能组件,因此我将类组件嵌套在这样的功能组件中:

//messages-list.container.tsx
//MessagesListContainer
export const MessagesListContainer = () => {
   const activeUser= useSelector((state:State) => getActiveUser(state));
   const messages= useSelector((state:State) => getMessagesList(state));
   return <MessagesList activeUser={activeUser} messages={messages} />
}


//Selectors
export const getActiveUser = (state: State) => state.activeUser;
export const getMessagesList = (state : State) => (
  Object.keys(state.messages).map((key : any)=> state.messages[key])
)

//end of messages-list.container.tsx

//messages-list.component.tsx
export interface IMessagesListProps {
  activeUser?: User;
  messages?: Message[];
}
/**
 *  Messages List
 */
export default class MessagesList extends PureComponent<IMessagesListProps> {
.
.
.
}

据我所知,最好将最后一级的组件与商店隔离开。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.