반응형
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데이터 액세스에 필요한 경우state의app.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
반응형
'programing' 카테고리의 다른 글
| Android에서 일반 Java 어레이 또는 ArrayList를 Json 어레이로 변환 (0) | 2023.03.06 |
|---|---|
| TS를 사용하는 Redx DevTools 확장과 관련된 오류: "속성 '_REDUX_DEVTOOLS_EXTION_COMPOSE__'이(가) '윈도' 유형에 없습니다." (0) | 2023.03.01 |
| 릴레이셔널 데이터베이스의 행을 삭제해야 합니까, 비활성화해야 합니까? (0) | 2023.03.01 |
| 인덱스와 함께 .map을 사용하여 반응합니다. (0) | 2023.03.01 |
| 0이 아닌 1페이지부터 시작하는 스프링 부트 페이지 설정을 하는 방법 (0) | 2023.03.01 |