我为正在制作的文件库做了一个非常简单的设置,它涉及一个主组件和两个子组件。图像预览当然有左箭头和右箭头,它们被传递并传递回来,这是一个创造性地称为";点击处理程序";它只是更新正在查看的文件的状态
但是,当调用clickHandler事件并创建一个临时变量以修改并发送回状态时,应用程序会因_this.state.activeFile is not a function
错误而崩溃。
然而,奇怪的是,这个状态是完全可读的。它可以完美地console.log()
,并且只有在尝试将其分配给变量以修改时才会出错。
以下是通过测试的子组件:
<FileView
file={this.props.media[this.state.activeFile]}
handler={this.clickHandler}
active={this.state.activeFile}
max={this.props.media.length}
/>
更多详细信息:https://i.stack.imgur.com/iccBD.png
这里是调用该方法的位置。
state={
activeFile: 2
}
clickHandler=(direction)=>{
console.log (this.state); // > Object { activeFile: 2 }
console.log (this.state.activeFile); // > 2
let temp = (this.state.activeFile) // 🛑 TypeError: _this.state.activeFile is not a function
// vvv Likely unrelated, but posted also for context
// evals left or right to plus or minus
(direction==="prev"?temp-=1:(direction==="next"?temp+=1:""))
this.setState({activeFile: temp})
}
更多详细信息:https://i.stack.imgur.com/lSkOX.png
正如您所看到的,数据是存在的、可读的,但不可分配。我从未见过这样的情况,也尝试过无数像this.state["activeFile"]
这样的解决方案,但都无济于事。
这一次真的让我大吃一惊,我很感激任何事先的帮助!
内容不专业的Codepen演示原型:
https://codepen.io/Jop/pen/vvJrqv
这不是react的东西,而是javascript的东西!带有错误的代码,你这样发布:
let temp = (this.state.activeFile) // 🛑 TypeError: _this.state.activeFile is not a function
// vvv Likely unrelated, but posted also for context
// evals left or right to plus or minus
(direction==="prev"?temp-=1:(direction==="next"?temp+=1:""))
但由于语法的工作方式,javascript将其视为
let temp = (this.state.activeFile)(direction==="prev"?temp-=1:(direction==="next"?temp+=1:""))
你可以看到它是如何认为它现在期望一个函数的;)如果你把它重写成
let temp = this.state.activeFile;
if (direction === "prev") {
temp -= 1;
} else if (direction === "next") {
temp += 1;
}
它应该工作:)
您可以查看此内容。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
<FileView handler={this.clickHandler.bind(this)} />
当您想根据前面的值修改您的状态时,不建议直接在setState
函数中使用this.state.[x]
,因为它很容易出错。
推荐的方法是使用this.setState(prevState => ({ }))
并使用previousState
中的变量。
此外,从您的函数中发送-1
和1
使处理变得更容易:
MediaViewer:
clickHandler = offset => event => {
this.setState(prevState => ({ activeFile: prevState.activeFile + offset }))
}
ActiveFile:
<div className="info-view_paging">
{props.active < 1 ? <div></div> : <div className="info_pager" onClick={props.handler(-1)}><button>previous</button></div>}
<div></div>
{props.max > props.active ? <div className="info_pager" onClick={props.handler(1)}><button>next</button></div> : <div></div>}
</div>
您收到错误,因为代码被解释为
let temp = (this.state.activeFile)(direction==="prev"?temp-=1:(direction==="next"?temp+=1:""))
因此,在ternary
函数之前添加分号或使用else if
语句
clickHandler=(supdawg)=>{
let temp = (this.state.activeFile);
(supdawg==="left" ? temp-=1 : (supdawg==="right") ? temp+= 1 : "");
this.setState({activeFile: temp});
}
或
clickHandler=(supdawg)=>{
let temp = (this.state.activeFile)
if (supdawg === "left") { temp -=1}
else if (supdawg === "right") { temp+=1}
else {temp = ""}
this.setState({activeFile: temp})
}