我使用回调函数selectionHandlerList()在父组件(AudiobookList)中从子组件(AudiobookDetail)中设置我的状态。当我运行以下代码时,会收到以下错误消息:"TypeError: this.setState不是函数“。
当在我的this.setState({ selectedAudiobook: someArg })函数中注释掉selectionHandlerList()时,我从子组件(from console.log(someArg) )接收期望的值,因此回调必须正常工作。
这是我的父组件的代码:
class AudiobookList extends Component {
constructor(props) {
super(props);
this.selectionHandlerList.bind(this);
}
state = {
audiobooks: [],
selectedAudiobook: null
}
componentWillMount() {
axios.get('http://www.demo.demo/api/get/all')
.then(response => this.setState({
audiobooks: response.data }))
.catch(e => console.log(e));
}
selectionHandlerList(someArg) {
this.setState({ selectedAudiobook: someArg });
console.log(someArg);
}
renderAudiobookChoice(audioBookChoice, selectionHandlerList) {
if (audioBookChoice === 'all') {
return (
this.state.audiobooks.map(audiobook =>
<AudiobookDetail
key={audiobook.id}
audiobook={audiobook}
selectionHandlerList={selectionHandlerList}
/>)
);
}
if (audioBookChoice === 'prose') {
return this.state.audiobooks.map(audiobook => {
return audiobook.text_type === 1 ?
<AudiobookDetail
key={audiobook.id}
audiobook={audiobook}
selectionHandlerList={selectionHandlerList}
/>
:
null;
});
}
if (audioBookChoice === 'poetry') {
return this.state.audiobooks.map(audiobook => {
return audiobook.text_type === 2 ?
<AudiobookDetail
key={audiobook.id}
audiobook={audiobook}
selectionHandlerList={selectionHandlerList}
/>
:
null;
});
}
}
render() {
console.log('ABL: ' + this.state.selectedAudiobook);
const selectionHandlerList = this.selectionHandlerList;
const { audioBookChoice } = this.props;
return (
<ScrollView>
{this.renderAudiobookChoice(
audioBookChoice,
selectionHandlerList
)}
</ScrollView>
);
}
}
export default AudiobookList;我的印象是,这个问题必须与binding this恰当地联系起来。但我无法从相关问题中找出答案。
任何帮助都是非常感谢的。
发布于 2018-07-16 15:51:16
对函数调用.bind将返回该函数的新版本。您已经调用了.bind,但是您还必须将函数重新分配到自身的“绑定”版本。
"TypeError: this.setState不是一个函数“几乎总是由这个简单的错误造成的。这样的事情应该能纠正这个问题:
constructor(props) {
super(props);
this.selectionHandlerList = this.selectionHandlerList.bind(this);
}React的这一部分解释了为什么会出现这种情况,https://reactjs.org/docs/components-and-props.html#es6-classes
另一种避免此问题的构造代码的方法是使用箭头函数类属性。例如:
selectionHandlerList = () => {
// this.[everything] works here, because `this`
//is preserved from outer scope within an arrow function
};这个特性仍然是一个提议,但它确实得到了babel的支持。您需要启用transform-class-properties或在Babel中启用stage-2来使用此语法。
https://stackoverflow.com/questions/51365688
复制相似问题