将this.props传递给另一个函数的容器会传递副本

时间:2018-10-30 16:36:29

标签: reactjs redux

我正在使用带有结构化选择器的redux,redux-actions和connect(react-redux)作为组件中的HOC。我在容器中绑定了一些调度程序和一些选择器的地方。

我现在想将我的一些容器逻辑外包给其他文件/函数,这些函数应该利用调度程序和容器的选定属性(容器的this.props)。

让我说我有一个名为demo的功能

function demo(props){
  // here is my logic where I work with some dispatchers 
  // and selected store properties of my container
}

现在在我的容器中,我这样调用演示函数

function CONTAINER_FUNC_XXX(){
    demo(this.props) 
}

我的演示函数以某种方式接收到属性的副本。 之所以得出这个结论,是因为在运行演示函数逻辑时,会调用一些调度程序,这些调度程序应该更改props的某些选择器属性,但不会发生。

因此,我想知道如何将指针传递给道具,而不是副本。以及为什么javascript会复制道具,因为它是一个深度嵌套的对象,它实际上应该只传递一个指针...

-------------------------------------------- ------------------编辑------------------------------- ----------------------------

这是一个更好的例子。

当我的mouseController.mouseDown被调用时,首先我启动demoDispatcher,它调用一个reducer,这个reducer操作demoStoreProp(实际上,此属性是一个数组,该数组被重置为空数组)。当我在mouseController中记录demoStoreProp时,它将返回错误的属性。由于我的调度程序动作都是同步的,因此我得出结论,控制器功能中的props参数是一个副本。

CONATINER

// MY CONTAINER APP

import * as mouseController from './mouseController'

class App extends React.Component {

   componentDidMount(){
     ...
     // here I am registering the classes/containers handleMouseDown function 
     // on the global/windows onmousedown event
     window.onmousedown = (e) => this.handleMouseDown(e);
     ...
   }

   handleMouseDown(e){
      // CONTROLLER CALL
      mouseController.mouseDown(e, this.props);

      // LOGS CORRECT VAR (empty array)
      console.log(this.props.demoStoreProp)
  };

  ...

}


// here are my store selected properties
const mapStateToProps = createStructuredSelector({
  ...
  demoStoreProp : [SELECTOR FUNC INSERTING THE PROP INTO THE CONTAINERS PROPS]
  ...
})

// here are my dispatcher properties
const mapStateToDispatch = {
  ...
  demoDispatch : [AN ACTION FROM AN ACTION CREATOR]
  ...
}

export default connect(
    mapStateToProps,
    mapStateToDispatch
)(App)

控制器

export function mouseDown(e, props){

  // calling the dispatcher with props
  props.demoDispatch();

  // LOGS WRONG VAR (filled array)
  console.log(props.demoStoreProp)

}

0 个答案:

没有答案