![](/img/trans.png)
[英]How can I set another state to pass data to from the initial state in a react class component
[英]How can I redirect to another component in react and pass the state that I set in the previous component?
我有一个要重定向到使用反应路由器的组件。 如何使用我在原始组件上选择的字符串设置新组件的 state? 我使用反应路由器的所有重定向都在工作,并且被重定向到的这个组件不起作用。 这是一个 html 按钮,单击时应使用初始数据呈现此新组件。
const Posts = (props) => {
const dispatch = useDispatch();
const getProfile = async (member) => {
console.log(member)
props.history.push('/member', { user: member});
console.log('----------- member------------')
}
const socialNetworkContract = useSelector((state) => state.socialNetworkContract)
return (
<div>
{socialNetworkContract.posts.map((p, index) => {
return <tr key={index}>
<button onClick={() => getProfile(p.publisher)}>Profile</button>
</tr>})}
</div>
)
}
export default Posts;
这是我试图在点击时重定向到的组件。
const Member = (props)=> {
const [user, setUser] = useState({});
const { state } = this.props.history.location;
const socialNetworkContract = useSelector((state) => state.socialNetworkContract)
useEffect(async()=>{
try {
await setUser(state.user)
console.log(user)
console.log(user)
const p = await incidentsInstance.usersProfile(state.user, { from: accounts[0] });
const a = await snInstance.getUsersPosts(state.user, { from: accounts[0] });
} catch (e) {
console.error(e)
}
}, [])
我在控制台中收到以下错误。
TypeError: Cannot read property 'props' of undefined
Member
src/components/profiles/member.js:16
13 | const [posts, setPosts] = useState([]);
14 | const [snInstance, setsnInstance] = useState({});
15 | const [accounts, setsAccounts] = useState({});
> 16 | const { state } = this.props.history.location;
如果您需要发送一些路由 state,则push
方法采用 object。
const getProfile = (member) => {
console.log(member)
props.history.push({
pathname: '/member',
state: {
user: member,
},
});
console.log('----------- member------------')
}
另外, Member
是一个函数组件,所以没有this
,只使用props
object。
路线 state 在location
道具上,而不是history
object。
const Member = (props)=> {
const [user, setUser] = useState({});
const { state } = props.location;
// access state.user
此外, useEffect
回调不能是async
的,因为它们必须返回 Promise,解释为效果清理 function。 您应该声明一个内部async
function 来调用。 最重要的是, setuser
function不是async
的,因此无法等待。
以下是我认为填充user
state 并发出副作用的效果:
// update user state when route state updates
useEffect(() => {
if (state && state.user) {
setUser(state.user);
}
}, [state]);
// run effect when user state updates
useEffect(() => {
const doEffects = async () => {
try {
const p = await incidentsInstance.usersProfile(state.user, { from: accounts[0] });
const a = await snInstance.getUsersPosts(state.user, { from: accounts[0] });
} catch (e) {
console.error(e)
}
}
doEffects();
}, [user]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.