我有一个名为“Pets”的状态的 redux 存储,它存储以下数组:
[{"id"2,"name":"Cat"},
{"id":3,"name":"Dog"},
{"id":4,"name":"Fish"}
]
在我的组件中,我像这样映射状态:(我使用 redux 表单和react-bootstrap-table)
class PetsPage extends Component {
constructor(props) {
super(props);
this.state =({
selected:[]
});
this.showRow = this.showRow.bind(this);
}
componentWillMount() {
this.props.fetchPets();
}
render() {
const {
handleSubmit,
previousPage,
pets
} = this.props
if (!pets){
return (
<div className="container">
<div> Loading...</div>
</div>
);
}
return (
<div className="container">
<BootstrapTable
data={pets}
search={true}
striped={true}
hover={true}
condensed={true}
selectRow={selectRowProp}>
<TableHeaderColumn dataField="id" isKey={true}>Pet #</TableHeaderColumn>
<TableHeaderColumn dataField="name">Company</TableHeaderColumn>
</BootstrapTable>
<p> Currently Chosen: <span> id: {this.state.selected}</span> </p>
<div className="btn-group">
<button type="button" onClick={previousPage} className="btn btn-success btn-lg"><i/> Previous</button>
<button type="submit" className="btn btn-success btn-lg">Next</button>
</div>
</div>
</form>
)
}
}
function mapStateToProps(state) {
return { pets: state.pets.all };
}
export default reduxForm({
form: 'wizard',
fields,
destroyOnUnmount: false,
validate
}, mapStateToProps, actions)(PetsPage)
到目前为止,一切正常。 当我像这样调用 pets Prop 时,我的问题就出现了:
<p> Currently Chosen: {pets[2].name}</p>
我不断收到此错误:
TypeError: pets[2] is undefined
理想情况下,我希望能够通过“选定”状态提供的 ID 来调用宠物的名称。
编辑--- 我注意到,如果我要转到另一个页面并返回到此页面,该代码实际上可以工作。这有点令人困惑,因为我认为拥有...装载容器可以防止这种情况发生。
最佳答案
如何获取pets
的初始状态?这些是异步检索的吗? (我怀疑是这样)
当您的 BootstrapTable
最初加载时,异步调用未完成,pets
仍未定义,因此出现错误。然后,当您转到另一个页面并返回此页面时,您的异步调用已完成,pets
现在是一个数组,并且它可以工作。
如果到目前为止我是对的,请在您的 BootstrapTable
中添加类似的内容:
if(this.props.pets) {
<p> Currently Chosen: {pets[2].name}</p>
... // render your pets props within the
} else {
// render some loading indicator
}
编辑:如果您的宠物被初始化为空数组,请检查宠物的长度而不是真值
关于reactjs - 在 React/Redux 中调用状态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38296710/