我正在使用React js。我有两个不同的功能。
第一:
componentDidMount() {
fetch("http://131.181.190.87:3001/all")
.then((res) => res.json())
.then((json) => {
this.setState({
isLoaded: true,
symbolsname: json,
items: json,
});
});
}
第二:
handleClick(symbol) {
fetch(`http://131.181.190.87:3001/history?symbol=${symbol}`)
.then((res) => res.json())
.then((json) => {
this.updateStateOfSymbols(json);
this.setState({
isLoad: true,
symbolsname: json,
});
});
}
服务器运行后,第一个函数首先被调用。服务器运行时,页面上会加载一个表,并且其中包含一些可单击的表数据或链接。当用户单击那些链接时,第二个函数被调用。但是,setState
对第二功能不起作用。当我尝试打印它时,我没有得到任何错误,只是说了它的undefined
。但是,如果我在第一个函数中将值传递给symbolsname
,则确实会显示输出。我假设您不能在不同的功能中两次使用setState
。有什么办法可以使其工作?
感谢您的帮助。谢谢
编辑:将json对象传递给函数handleclick
{filteredItems.map((item) => (
<tr>
<Link to="/symbols">
<td
key={item.symbol}
onClick={() => this.handleClick(item.symbol)}
>
{item.symbol}
</td>
</Link>
class AppComponent extends React.Component {
// Your version
handleClick (symbol) {
fetch(`http://131.181.190.87:3001/history?symbol=${symbol}`)
.then((res) => res.json())
.then((json) => {
// `This` is undefined if im not wrong
this.updateStateOfSymbols(json);
this.setState({
isLoad: true,
symbolsname: json,
});
});
}
// Mine
handleClick = (symbol) => {
fetch(`http://131.181.190.87:3001/history?symbol=${symbol}`)
.then((res) => res.json())
.then((json) => {
this.updateStateOfSymbols(json);
this.setState({
isLoad: true,
symbolsname: json,
});
});
}
render () {
// Your Version
<button onClick={e => handleClick.bind(this, e.target.values)}></button>
// My Version
<button onClick={e => handleClick(e.target.values)}>Testing</button>
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>