我是个反应迟钝的新手。点击一个按钮,一个学生被选中(这部分有效)。我想将该名称传递给子组件“bigProfile”,但我无法让它工作。
我正在这个分支上工作:https ://github.com/smilingkite/REACT-Evaluation-Tool-for-Teachers/tree/button
感谢@Jayabalaji JI 的回答,现在有一个应用组件如下:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import BigProfile from './components/bigProfile';
import fetchStudents from './actions/fetch';
import BigButton from './components/bigButton';
import ProfileListContainer from './components/profileListContainer';
export class App extends Component {
constructor(props) {
super(props);
this.state = {
studentName: ''
};
}
pickStudent(array) {
var index = Math.floor(Math.random() * array.length);
var student = array[index];
var studentName = student.name;
this.setState({ studentName: student.name });
console.log(studentName);
}
componentWillMount() {
this.props.fetchStudents();
}
render() {
const { students } = this.props;
return (
<div className="App">
<BigProfile name={this.state.studentName} />
<BigButton
onClick={() =>
this.pickStudent(selectStudentGroup(students, pickColor()))}
/>
<ProfileListContainer />
</div>
);
}
}
const mapStateToProps = store => {
return {
students: store.students
};
};
export default connect(mapStateToProps, { fetchStudents })(App);
大配置文件组件如下:
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
class BigProfile extends PureComponent {
static propTypes = {
name: PropTypes.string.isRequired
};
static defaultProps = {
name: '...'
};
componentWillReceiveProps(nextProps) {
if (this.props.name !== nextProps.name) {
this.setState((this.props.name: nextProps.name));
}
}
render() {
console.log('this.props (in render): ', this.props.name);
return (
<h1>
{'Ask a question of: '}
{this.props.name}
</h1>
);
}
}
export default BigProfile;
现在,单击 bigButton 后出现以下错误:“setState(...): 接受状态变量对象进行更新或返回状态变量对象的函数。” 它指的是 BigProfile 中的这一行:
this.setState((this.props.name: nextProps.name));