首页 > 解决方案 > ReactJS - 在组件之间传递数据

问题描述

我想在组件之间传递数据,但我遇到了问题。只要我还没有传递数据,就不会出现任何错误,这很好。当我尝试在控制台中显示道具时,我可以很容易地看到我想要的(history,match,location,AuthStore)。但是当我尝试传递数据时,我只能在控制台中看到valueAuthStore并且 value 返回空。我哪里错了?

front.layout.js

import Profile from '../../Views/profile'

const Layout = (props) => {
    const [user, setUser] = useState({});
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    props.AuthStore.getToken();
    const history = useHistory();


useEffect(() => {
    const token =
        props.AuthStore.appState != null
            ? props.AuthStore.appState.user.access_token
            : null;
    axios
        .post(
            "/api/authenticate",
            {},
            {
                headers: {
                    Authorization: "Bearer " + token,
                },
            }
        )
        .then((res) => {
            if (!res.data.isLoggedIn) {
                history.push("/login");
            }
            setUser(res.data.user);
            setIsLoggedIn(res.data.isLoggedIn);
        })
        .catch((error) => {
            history.push("/login");
        });
}, []);

return (
<>
    <Profile value={user} />
</>
)

index.js

const Profile = (props) => {
    console.log(props);
    const { params } = props.match;
    const [data, setData] = useState({});
    const history = useHistory();
if(props.location.key){
    useEffect(() => {
        axios
            .get(
                `/api/${params.username}`,

                {
                    headers: {
                        Authorization:
                            "Bearer " +
                            props.AuthStore.appState.user.access_token,
                    },
                }
            )
            .then((res) => {
                if (res.data.username) {
                    setData(res.data);
                }
            })
            .catch((error) => {
                console.log(error);
            });
            
    }, []);
}

标签: reactjs

解决方案


推荐阅读