连接在 Redux-react 中无法使用 Stateless 组件

Connect not working with StateLess component in Redux-react

本文关键字:Stateless 组件 Redux-react 连接      更新时间:2023-09-26

我正在从其他组件调度一个操作,并且存储正在使用svgArr属性进行更新,但是尽管以下无状态组件connect'ed存储,但当存储更改时svgArr它不会更新。

它是无状态组件的行为方式吗?还是我做错了什么?

const Layer = (props) => {
  console.log(props.svgArr);
  return (<div style = {
    {
      width: props.canvasWidth,
      height: props.canvasWidth
    }
  }
  className = {
    styles.imgLayer
  } > hi < /div>);
};
connect((state) => {
  return {
    svgArr: state.svgArr
  };
}, Layer);
export default Layer;

您似乎正在导出图层,而不是图层组件的连接版本。

如果您查看 redux 文档:https://github.com/reactjs/react-redux/blob/master/docs/api.md#inject-dispatch-and-todos

它应该是这样的

function mapStateToProps(state) {
  return {svgArr: state.svgArr}
}
export default connect(mapSTateToProps)(Layer)

这是对代码的重写

import {connect} from 'react-redux';
// this should probably not be a free variable
const styles = {imgLayer: '???'};
const _Layer = ({canvasWidth}) => (
  <div className={styles.imgLayer} 
       style={{
         width: canvasWidth,
         height: canvasWidth
       }}
       children="hi" />
);
const Layer = connect(
  state => ({
    svgArr: state.svgArr
  })
)(_Layer);
export default Layer;

如果你想连接无状态函数,你应该把它包装成 另一个常量:

const Layer = (props) => {
  return (
   <div > 
   </div>
 );
};
export const ConnectedLayer = connect(mapStateToProps)(Layer);

这里在 react native 中使用带有功能组件的 redux

从 'react-redux' 导入 { useSelector }

;

const variable = useSelector(state => state.user.variable)

此外,还可以传递具有功能组件的多个状态对象。

import {connect} from 'react-redux';
const PartialReview = ({auth, productreview}) => (
    <div className="row">
        <h2>{auth.uInfo._ubase}<h2>
        <p>{productreview.review_description}
    </div>
);
  const mapStateToProps = (state) => {
    return {auth: state.auth,productreview: state.productreview}
    };
  export default connect(mapStateToProps)(PartialReview)