首先,我想说,我知道关于这个话题有很多问题。我通读了其中的大部分内容,并仔细检查了我的代码,但我似乎无法让它工作。
我有以下子组件,其中包含一个图像,您可以通过单击该图像来更改该图像(您可以迭代 5 个图像的数组)。
export default class Images extends React.Component {
constructor(props) {
super(props);
this.changeIcon = this.changeIcon.bind(this);
this.state = {pointer: this.props.id-1, imgs: props.imgs };
}
changeIcon () {
const {length} = this.state.imgs;
const {pointer } = this.state;
const newPointer = pointer === length - 1 ? 0 : pointer+1;
this.setState({ pointer: newPointer });
this.props.onChangeIcon("I work");
}
render() {
const isclicked = this.props.clicked;
const { pointer, imgs } = this.state;
return(
<img src={imgs[pointer]} onClick={this.changeIcon}/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是父组件:
import Images from …Run Code Online (Sandbox Code Playgroud) 我在我的reactjs应用程序中使用受保护的路线,我想知道如何在受保护的路线中传递道具,或者是否有更优雅的方式来解决我的问题。
我觉得需要在受保护的路线中传递道具的原因是,注销按钮位于受保护的组件内,并且我需要与父组件进行通信,该组件包含用户正在尝试注销的所有路线。
以下是相关代码:
父组件:
render() {
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated === true
? <Component {...props} /*I tried inserting handleLogout={this.handleLogout} here */ />
: <Redirect to="/Login"/>
)} />
)
return (
<HashRouter basename={BASE_URL}>
<div className="stories-module">
<PrivateRoute
exact
path={'/login'}
component={Login}
/>
<PrivateRoute
exact
path={'/Main/'}
component={Main}
/>
</HashRouter>
)};
Run Code Online (Sandbox Code Playgroud)
不幸的是,我不知道该如何解决这个问题。
在路线组件中传递道具是否被认为是不好的做法?如果是这样,我还能如何处理?如果没有,我如何正确通过道具?
我有一个名为 UserSchema 的猫鼬模式,它存储有关所有用户的信息。我想让用户更改他的信息,我尝试使用 .findByIdAndUpdate。这是相关代码:
router.post("/updateprofile", function(req,res,next) {
const {id, org, tel, email, firstName, lastName} = req.body;
Users.findByIdAndUpdate(id, {org : org, tel : tel, email : email, firstName : firstName , lastName : lastName}, function (err, response) {
if (err) throw err
res.json(response);
});
});
Run Code Online (Sandbox Code Playgroud)
然而,试图改变信息的时候,我收到以下错误消息:Cannot read property 'password' of undefined。我很确定这是由预更新挂钩引起的,但我无法删除它,因为我的“忘记密码”功能需要它。这是代码:
UserSchema.pre('findOneAndUpdate', function (next) {
this.update({},{ $set: { password:
bcrypt.hashSync(this.getUpdate().$set.password, 10)}} )
next();
});
Run Code Online (Sandbox Code Playgroud)
我对它为什么使用那个 prehook 感到困惑,因为它在钩子中寻找findOneandUpdate以及当我尝试更改我正在使用的数据时findByIdAndUpdate。
我尝试使用,.update()但这也不起作用。有谁知道我做错了什么以及如何解决它?
我的ReactJS应用程序中有一个函数,该函数向服务器发送axios POST请求,以从数据库中删除某个元素。
基本上,我有一个列表,可以从中删除某些项目,但是,React仅显示刷新页面后通过删除元素所做的更改。
这是我使用的删除功能:
handleDelete (event) {
var id = event.target.id;
axios.get('todos/delete?id='+id)
.then(function(response) {
});
this.componentDidMount();
}
Run Code Online (Sandbox Code Playgroud)
componentDidMount()从我的数据库中获取数据并将其存储在状态中。我发现,如果我componentDidMount在函数内调用,它会立即显示更改,但是,我觉得这是一种非常不专业的方式来完成我要实现的目标。因此,我的问题是: