簡體   English   中英

如何在 react 中重定向到另一個組件並傳遞我在前一個組件中設置的 state?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM