我是reactjs的初学者,想知道为什么我的twitter-tweet按钮无法按预期工作。
预期行为:单击按钮应将报价复制到Twitter掩码
当前行为::单击按钮会产生const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props =>
isAuthenticated() ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: "/", state: { from: props.location } }} />
)
}
/>
);
,该消息显示在Twitter上。
有人可以告诉我解决此问题的方法吗?这是我的代码:
[object Object]--[object Object]
非常感谢:)
答案 0 :(得分:0)
代替传递定义的randomQuote和randomAuthor。
<a className="twitter-share-button" id="tweet-quote" href={`https://twitter.com/intent/tweet?text=${randomQuote}--${randomAuthor}`}>Tweet this one!</a>
尝试定义引号和作者。为了确保所需的状态和对象已经可用,只需在将内容分配给常量之前进行一些检查即可。
const selectedQuote = this.state.quotes[this.state.rndNum];
const quote = selectedQuote && selectedQuote.body;
const author = selectedQuote && selectedQuote.email;
并在您的退货中使用它,例如:
<a className="twitter-share-button" id="tweet-quote" href={`https://twitter.com/intent/tweet?text=${quote}--${author}`}>Tweet this one!</a>
为什么需要检查this.state.quotes[this.state.rndNum]
是否已经可用?
尽管您在componentWillMount()中触发了数据获取,但是并不能确保在第一次呈现状态后就用数据填充该状态。因此,您需要检查数据是否实际可用-否则,您将尝试访问根本不存在的数据,这将导致您遇到的错误。
另一个提示:请查看一下react组件的生命周期:
https://reactjs.org/docs/react-component.html
componentWillMount()
已过时,不应在React 16以后使用。
答案 1 :(得分:0)
感谢您的回复。不幸的是,答案与
render
目前我无法弄清楚为什么会这样。 在状态中创建rndNum的函数是否可能是此原因? 我会决定采取另一种解决方案:)
杜伊斯堡的问候。