Javascript 连接不与 Redux-react 中的 StateLess 组件一起工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35449317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:44:32  来源:igfitidea点击:

Connect not working with StateLess component in Redux-react

javascriptreactjsfunctional-programmingreduxredux-thunk

提问by sapy

I'm dispatching an action from some-other component , and store is getting updated with svgArrproperty, but though the following Stateless component connect'edto the store , it ain't getting updated when store changes for svgArr.

我正在从某个其他组件分派一个操作,并且 store 正在使用svgArr属性进行更新,但是尽管以下无状态组件connect'ed到 store ,但当 store 更改为 时它不会更新svgArr

Is it how it suppose to behave as it's a stateless component ? Or am I doing something wrong ?

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

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;

采纳答案by Thank you

Here's a rewrite of your code

这是你的代码的重写

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;

回答by sunnyto

You seem to be exporting Layer instead of the connected version of the Layer component.

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

If you look at the redux documentation: https://github.com/reactjs/react-redux/blob/master/docs/api.md#inject-dispatch-and-todos

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

It should be something like

它应该是这样的

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

回答by Hymankobec

If you want to connect the stateless function you should wrap it into the another const:

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

const Layer = (props) => {
  return (
   <div > 
   </div>
 );
};

export const ConnectedLayer = connect(mapStateToProps)(Layer);