【发布时间】:2018-01-30 04:06:28
【问题描述】:
当索引增加时,我无法让显示的组件更新。我现在可以控制正确的组件,但是因为 onClick 在需要更新的组件下方,所以它没有改变。有人可以帮我修复我的代码吗?我想我已经很接近了,但我一生都无法弄清楚。
这个注册页面是我想要更新组件的地方。本质上,我想在单击下一个按钮后显示数组中的每个组件。目前,功能控制台会按照我的意愿记录所有内容,只需让它出现在
返回错误“无法读取属性‘count’ of null”:
import React from 'react';
import Q1Name from './questions/Q1Name';
import Q2Birthday from './questions/Q2Birthday';
import Q3City from './questions/Q3City';
import Q4YouReady from './questions/Q4YouReady';
import Q5Setting from './questions/Q5Setting';
import Q6Length from './questions/Q6Length';
import Q7Email from './questions/Q7Email';
class SignUpPage extends React.Component {
constructor(props) {
super(props);
this.state = {
i: 0
}
}
_handleClick() {
const components = [Q1Name, Q2Birthday, Q3City, Q4YouReady, Q5Setting, Q6Length, Q7Email];
if(this.state.i < components.length) this.setState({ i : this.state.i + 1});
}
// handleIncrement() {
// this.setState({ count: this.state.count + 1});
// }}
render() {
const components = [Q1Name, Q2Birthday, Q3City, Q4YouReady, Q5Setting, Q6Length, Q7Email];
const componentsToRender = components.map((Component, i) => (
<Component key={i} />
));
return (
<div className = "container-fluid signup-page">
<div className = "question-box">
{componentsToRender[this.state.i]}
<button type="submit" className="btn btn-custom btn-lg" onClick={() => this._handleClick}>Next Question!</button>
</div>
</div>
);
}
}
export default SignUpPage;
我引入了一些组件类型,年龄、生日、电子邮件和一些按钮点击等。
import React from 'react';
class Q1Name extends React.Component {
handleSubmit(event) {
event.preventDefault();
this.props.onNext();
}
render() {
return (
<div className="questions q1" style={this.props.style}>
<h1 id="question-h1">What is your name?</h1>
<form>
<div className="form-group">
<input type="name" className="form-control text-form custom-form" id="nameInput" aria-describedby="name" placeholder="" />
</div>
{/* <button type="submit" className="btn btn-custom btn-lg" onSubmit={this.handleSubmit}>Next Question!</button> */}
</form>
</div>
);
}
}
export default Q1Name;
这里是按钮选项组件的示例:
import React from 'react';
class Q5Setting extends React.Component {
render() {
return (
<div className="questions">
<h1 id="question-h1">What is your ideal setting?</h1>
<button type="button" className="btn btn-custom-select btn-lg">Take me to the beach!</button>
<button type="button" className="btn btn-custom-select btn-lg">Anywhere outdoors!</button>
<button type="button" className="btn btn-custom-select btn-lg">All about the city!</button>
</div>
);
}
}
export default Q5Setting;
任何帮助解决这个问题将不胜感激!
【问题讨论】:
-
你认为你的哪一行代码会改变或更新什么?
-
现在,onClick 函数正在正确更新索引和控制台记录下一个组件,但我不确定我需要做什么才能真正更新显示的组件。
-
哦,您认为更改
i会更新您的观点吗?你读过关于state的反应吗?这就是你要找的。 reactjs.org/docs/state-and-lifecycle.html -
我更新为添加状态,但我认为我做的不正确。它无法读取 null 的属性计数。我对反应很陌生,所以只是想学习和理解。我更新了我最初帖子中的代码以反映
标签: javascript arrays reactjs react-router react-redux