Javascript 状态更改时从阵列渲染嵌套组件
我有一个React父组件,我使用graphql将json数据作为道具导入子组件。我试图使用state在单击时使用json文件中的三个对象之一更新页面Javascript 状态更改时从阵列渲染嵌套组件,javascript,reactjs,jsx,array.prototype.map,Javascript,Reactjs,Jsx,Array.prototype.map,我有一个React父组件,我使用graphql将json数据作为道具导入子组件。我试图使用state在单击时使用json文件中的三个对象之一更新页面 class Work extends React.Component { constructor(props) { super(props); this.state = { data: [] } } componentDidMount(){ this.setState({data: data
class Work extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
}
}
componentDidMount(){
this.setState({data: data.dataJson[0]})
console.log(data.dataJson[0])
}
showPsContent() {
this.setState({data: data.dataJson[1]})
}
render() {
console.log(this.props)
const {data} = this.props
console.log(data)
console.log(this.props.data)
return (
<div id='work'>
<NavBar/>
<div className='work-content'>
<div className="side-nav">
<button onClick={() =>
this.showContent(index)}></button>
</div>
<h1 className="work-header"></h1>
<Page data={this.state.data}/>
</div>
</div>
)
}
}
我假设您在componentDidMount中获取数据。之后,您可以将当前页码/索引存储在状态中,并在单击按钮时增加/更改它。所以,当您增加/更改页面索引时,组件将重新加载childs,一切正常。您的组件可以这样编写:
class Work extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
currentPageIndex: 0
}
}
componentDidMount() {
// getting data somehow
this.setState({data: jsonData});
}
showContent() {
const nextIndex = this.state.currentPageIndex === this.state.data.length ? 0 : this.state.currentPageIndex + 1;
this.setState({currentPageIndex: nextIndex});
}
render() {
const {data, currentPageIndex} = this.state;
return (
<div id='work'>
<NavBar />
<div className='work-content'>
<div className="side-nav">
<button onClick={this.showContent}></button>
</div>
<h1 className="work-header"></h1>
<Page data={data ? data[currentPageIndex] : null} />
</div>
</div>
)
}
}
课堂作业扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
数据:[],
currentPageIndex:0
}
}
componentDidMount(){
//以某种方式获取数据
this.setState({data:jsonData});
}
showContent(){
const nextIndex=this.state.currentPageIndex==this.state.data.length?0:this.state.currentPageIndex+1;
this.setState({currentPageIndex:nextIndex});
}
render(){
const{data,currentPageIndex}=this.state;
返回(
)
}
}
graphql查询(未显示)中的数据在构建过程中创建并作为道具传递后,我实际上能够以状态存储数据。我稍微调整了一下,使初始状态为第一个数组,然后showContent函数增加了数组并设置了状态。
class Work extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
currentPageIndex: 0
}
}
componentDidMount() {
// getting data somehow
this.setState({data: jsonData});
}
showContent() {
const nextIndex = this.state.currentPageIndex === this.state.data.length ? 0 : this.state.currentPageIndex + 1;
this.setState({currentPageIndex: nextIndex});
}
render() {
const {data, currentPageIndex} = this.state;
return (
<div id='work'>
<NavBar />
<div className='work-content'>
<div className="side-nav">
<button onClick={this.showContent}></button>
</div>
<h1 className="work-header"></h1>
<Page data={data ? data[currentPageIndex] : null} />
</div>
</div>
)
}
}