简体   繁体   English

React-从另一个文件更新状态的组件

[英]React - Updating State's Component From Another File

Suppose that I had a React component such as 假设我有一个React组件,例如

    import { getEventListener } from 'controls';
    class SomeComponent extends React.Component {
          render() {
             return (<div onClick={this.handleEvent}></div>) 
          }

          handleEvent = (event) => {
             getEventListener(event, this);
          }
    }

And I have another file such as 我还有另一个文件,例如

   export function getEventListeners(event, component) {
       component.setState({x: 1};
   }

If getEventListeners calls set state from the component to change one of the properties would it cause an issue? 如果getEventListeners调用组件中的设置状态以更改属性之一,会引起问题吗?

This causes the design issue, passing the whole component by reference and accessing it in a function breaks the principle of least privilege . 这会导致设计问题,通过引用传递整个组件并在函数中访问它会破坏最小特权原则 Calling the function with a context like getEventListener.call(this, event) would have the same problem. 使用诸如getEventListener.call(this, event)类的上下文调用该函数将具有相同的问题。

If getEventListener isn't supposed to be reused between components, it shouldn't be extracted from a component where it's used. 如果不应在组件之间重用getEventListener ,则不应从使用它的组件中提取它。 It uses this.setState method and clearly belongs to a class. 它使用this.setState方法,并且显然属于一个类。 In case multiple inheritance is involved, a mix-in can be used. 如果涉及多个继承,则可以使用混合。

A solution that is idiomatic to React is reusable state updater function . 可重用的状态更新器功能是React惯用的解决方案。 It's decoupled from a component and supposed to be used for pure synchronous functions: 它与组件分离,应该用于纯同步功能:

   export const getEventListeners = event => state => {
     // return state object that derives from an event
   };

   ...

   this.setState(getEventListeners(event));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM