gpt4 book ai didi

javascript - 仅当我从主页启动流程时组件才会呈现

转载 作者:行者123 更新时间:2023-12-03 00:28:25 25 4
gpt4 key购买 nike

我的应用程序遇到问题。我的用户组件仅在我从主页启动应用程序然后单击那里的用户链接时加载 UserCard...如果我只是刷新用户 URL...UserCard 未加载,这意味着我的 this. props.users。我确实在 chrome 中看到它说:当我刷新时,下面的值刚刚被评估,但当我浏览流程时,它并没有这么说。任何帮助将不胜感激。

App.js

class App extends Component {
constructor(props) {
super(props);

this.state = {
users: []
};
}

componentDidMount() {
users = []
axios.get('/getall').then((res) => {
for(var d in res.data) {
users.push(new User(res.data[d]));
}
});
this.setState({ users });
}

render() {
const { users } = this.state;
return (
<Router history={history}>
<Switch>
<PrivateRoute exact path="/" component={Home} />
<Route exact path='/users' render={(props) => <Users {...props} users={users} />}/>
</Switch>
</Router>
)
}
}

私有(private)路线:

export const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
<Component {...props} /> )} />
)

用户.js

export default class Users extends Component {
render() {
console.log(this.props.users);
return (
<Row>
{this.props.users.map(u =>
<UserCard key={u.name} user={u}/>
)}
</Row>
);
}
}

export class User {
constructor(obj) {
for (var prop in obj){
this[prop] = obj[prop];
}
}

getURLName() {
return this.name.replace(/\s+/g, '-').toLowerCase();
}
}

class UserCard extends Component {

render() {
return (
<Link to={'/users/' + this.props.user.getURLName()} >
<div>
// Stuff Here
</div>
</Link>
);
}
}

最佳答案

根据评论:

这里的问题是你如何设置状态。您永远不应该直接修改状态,因为这不会导致组件重新渲染 See the react docs

与问题无关的一些其他想法:

  • 根据评论 - 尽可能使用函数组件,尤其是 hooks在路上
  • 可能不需要创建User类,只需new创建小的用户对象。只需使用普通的旧 JS 对象并在其使用的位置计算链接 url:
<小时/>
render() {
const { user } = this.props
return <Link to={`/users/${user.name.replace(/\s+/g, '-').toLowerCase()}`} />
}
  • 开始使用 eslint 等 linter 可能是个好主意。我发现您在声明 users = [] 时没有使用 letconst (不要使用 var )。这是不好的做法,因为以这种方式创建变量会污染全局 namespace 。像 eslint 这样的 Linters 将帮助您在编码时捕获此类问题。

关于javascript - 仅当我从主页启动流程时组件才会呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53979335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com