我目前通过道具将数据传递到我的组件中,并且出于某种原因,它显示为未定义。
从我的父组件角度来看,我有以下第2道具,data
和header
。
class ContractTable extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
render() {
return (
<div>
<p></p>
<MuiThemeProvider>
<TableTest
data={this.state.data}
header={[
{
name: "First Name",
prop: "firstName"
},
{
name: "Last Name",
prop: "lastName"
},
{
name: "Age",
prop: "age"
},
{
name: "Height",
prop: "height"
},
{
name: "Address",
prop: "address"
}
]}
/>
</MuiThemeProvider>
<p></p>
</div>
);
}
我尝试抓住道具并将其设置为我的状态,但是当我记录this.props.data
或this.props.header
时,它会返回undefined。为什么是这样?
import React, { Component } from 'react';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';
class TableTest extends Component {
constructor(props) {
super(props);
this.state = {
data: props.data,
header: props.header
}
this.row = this.row.bind(this);
}
row = (currentValue, index, header) => (
<TableRow key={`t-${index}`}>
{
header.map((headerName, index) => (
<TableRowColumn key={`trc-${index}`}>
{currentValue[headerName.prop]}
</TableRowColumn>
))
}
</TableRow>
);
render() {
return 'hello'
}
}
export default TableTest;
答案 0 :(得分:2)
更新:查看https://jsfiddle.net/nroLmghv/
刚刚呈现简单的表头。
将道具传递给州并不是一个好方法。
我创建了一个代码段。它看起来很有效。指出哪个地方有问题。或者提供MuiThemeProvider
和TableTest
完整代码。
class Example extends React.Component {
constructor(props) {
super(props)
this.state = {
// mock value
data: "some value"
}
}
render() {
return <div>
<TableTest
data={this.state.data}
header={[
{
name: "First Name",
prop: "firstName"
},
{
name: "Last Name",
prop: "lastName"
},
{
name: "Age",
prop: "age"
},
{
name: "Height",
prop: "height"
},
{
name: "Address",
prop: "address"
}
]}
/>
</div>;
}
}
class TableTest extends React.Component {
constructor(props) {
super(props);
this.state = {
data: this.props.data,
header: this.props.header
}
console.log(this.state.data)
console.log(this.state.header)
}
render() {
return <div></div>;
}
}
ReactDOM.render(
<Example />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root">
</div>
答案 1 :(得分:0)
它是一个反模式来设置一个可以直接从道具派生的状态,你宁愿直接使用道具。此外,如果你使用道具设置状态,你需要根据道具变化更新状态,你还需要实现componentWillReceiveProps
功能