【问题标题】:Connect not working with StateLess component in Redux-reactConnect 在 Redux-react 中无法使用 StateLess 组件
【发布时间】:2016-05-28 17:18:45
【问题描述】:

我正在从其他组件调度一个动作,并且 store 正在使用 svgArr 属性进行更新,但是尽管以下无状态组件 connect'ed 到 store ,但当 @ 的 store 更改时它不会更新987654323@.

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

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;

【问题讨论】:

    标签: javascript reactjs functional-programming redux redux-thunk


    【解决方案1】:

    您似乎正在导出 Layer 而不是 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)

    【讨论】:

    • 太棒了。我只是想通了。即将更新答案。但是看到你已经想通了。谢谢。
    【解决方案2】:

    这是你的代码的重写

    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 mapStateToProps = (state) =>{ return{ authentication :state.authentication, } } const Constants = (props)=> ({ BASE_URL: props.authentication.baseurl } ) 导出默认连接(mapStateToProps)(常量);你能告诉我现在该怎么办吗?
    【解决方案3】:

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

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

    【讨论】:

    • 我们为什么要这样做?我们可以export default connect(... 吗?
    【解决方案4】:

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

    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)
    

    【讨论】:

      【解决方案5】:

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

      从 'react-redux' 导入 { useSelector };

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

      【讨论】:

        猜你喜欢
        • 2021-10-21
        • 2021-02-24
        • 2018-09-09
        • 2018-06-28
        • 2018-06-06
        • 2018-09-10
        • 2018-11-03
        • 1970-01-01
        • 2020-04-25
        相关资源
        最近更新 更多