Javascript 如何重定向到react中的另一个组件并传递在前一个组件中设置的状态?

Javascript 如何重定向到react中的另一个组件并传递在前一个组件中设置的状态?,javascript,reactjs,react-router,react-router-dom,Javascript,Reactjs,React Router,React Router Dom,我有一个组件我想重定向到使用反应路由器。如何使用在原始组件上选择的字符串设置新组件的状态?我所有使用react路由器的重定向都在工作,而被重定向到的组件不工作。它是一个html按钮,当单击时,应使用初始数据呈现此新组件 const Posts = (props) => { const dispatch = useDispatch(); const getProfile = async (member) => { console.log(member) pr

我有一个组件我想重定向到使用反应路由器。如何使用在原始组件上选择的字符串设置新组件的状态?我所有使用react路由器的重定向都在工作,而被重定向到的组件不工作。它是一个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;
我在控制台中得到以下错误

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;

如果需要发送一些路由状态,那么
push
方法将获取一个对象

const getProfile = (member) => {
  console.log(member)
  props.history.push({
    pathname: '/member',
    state: {
      user: member,
    },
  });
  console.log('----------- member------------')
}
此外,
成员
是一个功能组件,因此没有
,只需使用
道具
对象即可

const Member = (props)=> {  
  const [user, setUser] = useState({});
  const { state } = props.location;

  // access state.user
路由状态在
位置
道具上,而不是
历史
对象上

const Member = (props)=> {  
  const [user, setUser] = useState({});
  const { state } = props.location;

  // access state.user
另外,
useffect
回调不能是
async
,因为它们必须返回一个承诺,解释为效果清理函数。您应该声明要调用的内部
async
函数。除此之外,
setuser
函数不是异步的,因此不能等待

以下是我认为填充
用户
状态和发布副作用的效果:

// 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]);

谢谢你。我试过了,它只是一直在加载,并且状态没有在新服务器上实例化component@JohnBradshaw是的,我试着说react状态更新不能等待。我已经更新了我的答案,我认为这些都是你之前尝试做的工作的效果。