最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React js access to the state of another class - Stack Overflow

programmeradmin0浏览0评论

How can I access the state of another class.
This construction does not work

class classname2 extends React.Component {
  ...
  this.state = { statename1: "lala" };
  ...
};

class classname1 extends React.Component {
  render() {
    return (
       {classname2.state.statename1 } 
    );
  }
};

How can I access the state of another class.
This construction does not work

class classname2 extends React.Component {
  ...
  this.state = { statename1: "lala" };
  ...
};

class classname1 extends React.Component {
  render() {
    return (
       {classname2.state.statename1 } 
    );
  }
};

Share Improve this question asked Aug 13, 2017 at 21:16 Маргарита КорниловаМаргарита Корнилова 11 gold badge1 silver badge4 bronze badges 1
  • 2 This is an anitpattern. You should instead, pass in props from ClassName2 into ClassName1 to access the data. – styfle Commented Aug 13, 2017 at 21:23
Add a ment  | 

2 Answers 2

Reset to default 5

As mentioned in the ments, pass state as props to their children.

class classname2 extends React.Component {
  this.state = { statename1: "lala" };
  render() {
    return <classname1 statename1={this.state.statename1} />
  }
};

class classname1 extends React.Component {
  render() {
    return (
       <div>{this.props.statename1}</div>
    );
  }
};

An often used pattern is passing arbitrary props down the ponent tree:

const {needThisOne, andThisOne, ...props} = this.props;
// do stuff with needThisOne andThisOne
// and pass the remaining props down:
return <Component {...props} />;

An update for hooks, because why not.

const ParentComponent = ({...props}) => {
   const [stateName1, setStateName1] = useState('defaultValue');
   return <ChildComponent stateName1={stateName1} {...props} />;
}

const ChildComponent = ({stateName1, ...props}) => (
    <span>{stateName1}</span>
);

Shared state between ponents by direct access is an anti-pattern. Each ponent should have its own state. If you need globally a available state, please consider using Redux.

It may sound a bit cumbersome at first but it's awesome and it allows your app to be properly tested.

Edit:

Passing state as props is also valid, but it only works when ponents are in parent-child order. Redux allows ponents to be updated no matter what their relationship is

发布评论

评论列表(0)

  1. 暂无评论