programing

React에서 하위 상태의 상위 상태 액세스

fastcode 2023. 3. 1. 13:48
반응형

React에서 하위 상태의 상위 상태 액세스

React에는 (예를 들어) 2개의 컴포넌트가 있습니다.첫 번째는app.js는 루트 컴포넌트입니다.일부 Import 합니다.JSON데이터 및 데이터 저장하다state이 기능은 정상적으로 작동합니다(React devtools에서 확인할 수 있습니다).

import data from '../data/docs.json';

class App extends Component {
  constructor() {
    super();
    this.state = {
      docs: {}
    };
  }
  componentWillMount() {
    this.setState({
      docs: data
    });
  }
  render() {
    return (
      <Router history={hashHistory}>
        <Route path="/" component={Wrapper}>
          <IndexRoute component={Home} />
          <Route path="/home" component={Home} />
          <Route path="/docs" component={Docs} />
        </Route>
      </Router>
    );
  }
}

두 번째는docs.js는, 이것을 표시하는 것을 목적으로 하고 있습니다.JSON데이터 액세스에 필요한 경우stateapp.js지금으로서는 오류가 발생하고 있습니다(이유는 알고 있습니다).this포함하지 않음app.js). 그런데 어떻게 하면state부터app.js로.docs.js?

class Docs extends React.Component {
    render() {
        return(
            <div>
                {this.state.docs.map(function(study, key) { 
                    return <p>Random text here</p>; 
                })}
            </div>
        )
    }
}

이를 위한 적절한 방법은 다음과 같이 주를 통과시키는 것입니다.props로.Docs요소.

단, 당신이 사용하고 있기 때문에React Router다음과 같은 방법으로 액세스 할 수 있습니다.this.props.route.param디폴트 대신this.props.param

따라서 코드는 대략 다음과 같습니다.

<Route path="/docs" component={Docs} docs={this.state.docs} />

그리고.

{this.props.route.docs.map(function(study, key) { 
    return <p>Random text here</p>; 
})}

또 다른 방법은 다음과 같습니다.

<Route path="/docs" component={() => <Docs docs={this.state.docs}/>}>

어린이를 합격시켜야 하는 경우:

<Route path="/" component={(props) => <Docs docs={this.state.docs}>{props.children}</Docs>}>

이렇게 하면 소품 가치에 직접 접근할 수 있습니다.this.props.docs하위 구성 요소:

{
    this.props.docs.map((study, key)=> { 
       return <p key={key}>Random text here</p>; 
    })
}

또 다른 방법은

        <Route path='/' render={ routeProps => <Home 
            {...routeProps} 
            docs={this.state.docs}
            /> 
          } 
        />

하위 구성 요소에서 액세스할 수 있는 동안docs사용.

this.props.docs

도움이 됐으면 좋겠다!

언급URL : https://stackoverflow.com/questions/41825557/accessing-parent-state-in-child-in-react

반응형