用户输入并命名并根据搜索条件映射用户列表。结果按等级排序:
(resultsOrder = rank.map(id => results.get(id))
对于每个结果,用户pic,名字和姓氏与添加按钮一起显示(因为仅显示不是朋友的人)。按下此按钮后,友谊将添加到数据库中。
然而onClick我也希望按钮改变:
<Button name="Add" style="blue" onClick={() => addFriend(userId, r.user_id)} />
为:
<p> - Request Sent - </p>
但我不知道如何更改地图循环中的其中一个按钮?
示例,
=&GT; 显示搜索结果:
Bob Smith ADD
Bob Smithies ADD
=&GT; 按下Bob Smith后:
Bob Smith - 请求已发送 -
Bob Smithies ADD
如果这不容易实现:在添加之后从列表中删除特定结果,但之前显示警报(&#34;发送的朋友请求&#34;)是可以接受的。
rank: List(...)
0: "3"
1: "2"
2: "1"
3: "4"
results: Map(...)
0: Array[2]
0: "2"
1: Record(...)
0: Array[2]
0: "user_id"
1: "2"
1: Array[2]
0: "firstName"
1: "Bob"
2: Array[2]
0: "lastName"
1: "Smith"
...
class ShowResults extends Component {
constructor(props) {
super(props)
this.state = {}
}
render() {
const { inviteFriend, results, rank, userId, addFriend } = this.props
const resultsOrdered = rank.map(id => results.get(id))
return (
<div>
<div>
<table>
<tbody>
{resultsOrdered.map(
(r, friendId) =>
(
<tr key={r.user_id}>
<td>
<img src={r.picUrl} />
</td>
<td>
{r.firstName} {r.lastName}
</td>
<Button name="Add" style="blue" onClick={() => addFriend(userId, r.user_id)} />
</tr>
)
)}
</tbody>
</table>
</div>
</div>
)
}
}
export default ShowResults
答案 0 :(得分:1)
在处理程序中,您可以更新列表以更新按钮文本。
根据我的理解,我尝试创建以下代码段。希望这可以帮助。
const list = [
{
name: "Bob Smith",
id:1
},
{
name: "Martin Cooper",
id:2
},
{
name: "Bob Smithies",
id:3
},
{
name: "David",
id:4
}
];
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
list: list
};
this.addFriend = this.addFriend.bind(this);
}
some() {
console.log("done:")
}
addFriend(item) {
let updatedList = this.state.list.map(obj => {
if(obj.id === item.id) {
return Object.assign({}, obj, {
updatedLabel: "Request Sent"
});
}
return obj;
});
this.setState({
list : updatedList
}, () => {
this.some()
});
}
addFriendAndHide(item) {
let updatedList = this.state.list.filter(obj => {
if(obj.id === item.id) {
return false;
}
return true;
});
this.setState({
list : updatedList
});
}
render() {
return (
<div>
<table>
<tbody>
{this.state.list.map(item =>
<tr key={item.itemId}>
<td>
{item.name}
</td>
<td>
<button
className="delete"
onClick={() => this.addFriend(item)}
>
{item.updatedLabel || "Add"}
</button>
</td>
<td>
<button
className="delete"
onClick={() => this.addFriendAndHide(item)}
>
{"Hide after request is sent"}
</button>
</td>
</tr>
)}
</tbody>
</table>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
&#13;
table td {
font-size: 14px;
font-weight: normal;
padding: 10px;
border: 1px solid #eee;
}
&#13;
<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="app"></div>
&#13;
<强>更新强>
是的,您可以在状态更改异步后调用任何fn,如下所示:
this.setState({
... //update label by updating list
}, ()=> {
this.addFriend()
});